<template>
  <div class="game-learning">
    <!-- 页面头部 -->
    <div class="page-header">
      <button class="back-btn" @click="goBack">
        ← 返回
      </button>
      <h1>🎮 单词游戏</h1>
      <div class="header-stats">
        <div class="stat-item clickable" @click="showLeaderboard">
          <span class="stat-icon">⭐</span>
          <span class="stat-value">{{ totalStars }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-icon">🏆</span>
          <span class="stat-value">{{ completedLevels }}/{{ totalLevels }}</span>
        </div>
        <div class="stat-item clickable" @click="showProgressView">
          <span class="stat-icon">📊</span>
          <span class="stat-value">{{ progressPercentage }}%</span>
        </div>
      </div>
    </div>

    <!-- 难度选择界面 -->
    <div v-if="currentView === 'difficulty'" class="difficulty-selection-container">
      <div class="difficulty-title">
        <h2>🎯 选择难度</h2>
        <p>选择适合你的难度开始挑战吧！</p>
      </div>
      <div class="difficulty-cards">
        <div
          v-for="difficulty in difficulties"
          :key="difficulty.value"
          class="difficulty-card"
          :class="difficulty.value"
          @click="selectDifficulty(difficulty.value)"
        >
          <div class="difficulty-icon">{{ difficulty.icon }}</div>
          <div class="difficulty-name">{{ difficulty.name }}</div>
          <div class="difficulty-desc">{{ difficulty.description }}</div>
          <div class="difficulty-stats">
            <div class="stat">
              <span class="stat-label">关卡数</span>
              <span class="stat-value">{{ difficulty.levelCount }}</span>
            </div>
            <div class="stat">
              <span class="stat-label">已完成</span>
              <span class="stat-value">{{ getCompletedCountByDifficulty(difficulty.value) }}/{{ difficulty.levelCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 游戏地图界面 -->
    <div v-if="currentView === 'map'" class="game-map-container">
      <div class="map-title">
        <button class="back-to-difficulty-btn" @click="backToDifficulty">← 返回难度选择</button>
        <h2>🗺️ {{ currentDifficultyName }} - 冒险地图</h2>
        <p>选择关卡开始挑战吧！</p>
      </div>
      
      <div class="map-wrapper">
        <!-- 地图背景 -->
        <div class="map-background">
          <!-- 地图装饰元素 -->
          <div class="map-decoration cloud cloud-1">☁️</div>
          <div class="map-decoration cloud cloud-2">☁️</div>
          <div class="map-decoration tree tree-1">🌳</div>
          <div class="map-decoration tree tree-2">🌲</div>
          <div class="map-decoration mountain">⛰️</div>
        </div>
        
        <!-- 滑动容器 -->
        <div class="map-scroll-container" ref="scrollContainer">
          <!-- 关卡容器 -->
          <div class="levels-container" :style="{ transform: `translateX(${scrollOffset}px)` }">
            <!-- 地图路径 -->
            <div class="map-path-line"></div>
            <div
              v-for="(level, index) in gameLevels"
              :key="level.id"
              class="level-node"
              :class="{
                'completed': level.completed,
                'attempted': level.attempted && !level.completed,
                'current': level.unlocked && !level.completed && !level.attempted,
                'locked': !level.unlocked
              }"
              @click="selectLevel(level)"
            >
              <!-- 关卡点 -->
              <div class="level-point">
                <!-- 完成标记 -->
                <div v-if="level.completed" class="trophy-icon">🏆</div>
                <!-- 关卡图标 -->
                <div v-else-if="level.unlocked" class="level-icon-circle">
                  <span class="unlock-icon">{{ level.icon }}</span>
                </div>
                <!-- 锁定图标 -->
                <div v-else class="level-icon-circle locked">
                  <span class="lock-icon">🔒</span>
                </div>
              </div>
              
              <!-- 关卡信息卡片 -->
              <div class="level-info-card">
                <div class="level-number">第{{ level.level }}关</div>
                <div class="level-name">{{ level.name }}</div>
                <div v-if="level.attempted || level.completed" class="level-stars">
                  <span v-for="i in level.stars" :key="i" class="star">⭐</span>
                  <span v-for="i in (3 - level.stars)" :key="'empty-' + i" class="star empty">☆</span>
                </div>
              </div>
              
              <!-- 闪烁效果 -->
              <div v-if="level.unlocked && !level.completed" class="pulse-ring"></div>
            </div>
          </div>
        </div>
        
        <!-- 滑动控制按钮 -->
        <div class="map-controls">
          <button 
            class="scroll-btn scroll-left" 
            :disabled="scrollOffset >= 0"
            @click="scrollLeft"
          >
            ←
          </button>
          <button 
            class="scroll-btn scroll-right" 
            :disabled="scrollOffset <= maxScrollOffset"
            @click="scrollRight"
          >
            →
          </button>
        </div>
      </div>
    </div>

    <!-- 游戏任务界面 -->
    <div v-if="currentView === 'game'" class="game-task-container">
      <div class="task-header">
        <div class="level-info-header">
          <h2>{{ currentLevel.name }}</h2>
          <p>{{ currentDifficultyName }} - 第{{ currentLevel.level }}关</p>
        </div>
        <div class="progress-info">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: `${(currentQuestionIndex / questions.length) * 100}%` }"></div>
          </div>
          <span class="progress-text">{{ currentQuestionIndex + 1 }}/{{ questions.length }}</span>
        </div>
      </div>

      <div class="task-content">
        <!-- 单词显示区域 -->
        <div class="word-display">
          <div class="word-text" :class="{ 'letter-display': isLetterQuestion }">
            {{ currentQuestion.word }}
          </div>
          <!-- 选择后才显示意思、音标和例句 -->
          <div v-if="showAnswer && !isLetterQuestion && currentQuestion.chinese" class="word-details">
            <div class="word-meaning">
              <span class="meaning-label">意思：</span>
              <span class="meaning-text">{{ currentQuestion.chinese }}</span>
            </div>
            <div v-if="currentQuestion.phonetic" class="word-phonetic">
              <span class="phonetic-label">音标：</span>
              <span class="phonetic-text">/{{ currentQuestion.phonetic }}/</span>
            </div>
            <div v-if="currentQuestion.examples && currentQuestion.examples.length > 0" class="word-examples">
              <div class="examples-label">例句：</div>
              <div 
                v-for="(example, index) in currentQuestion.examples" 
                :key="index" 
                class="example-item"
              >
                <div class="example-en">{{ example.en }}</div>
                <div class="example-cn">{{ example.cn }}</div>
              </div>
            </div>
          </div>
          <button class="play-sound-btn" @click="playWordSound(currentQuestion.word)">
            <span class="sound-icon">🔊</span>
            <span>播放发音</span>
          </button>
        </div>

        <!-- 图片选项区域 -->
        <div class="options-grid">
          <div
            v-for="(option, index) in currentQuestion.options"
            :key="index"
            class="option-card"
            :class="{
              'correct': selectedAnswer === index && option.isCorrect,
              'wrong': selectedAnswer === index && !option.isCorrect,
              'highlight-correct': showAnswer && option.isCorrect,
              'shake': selectedAnswer === index && !option.isCorrect
            }"
            @click="selectAnswer(index)"
          >
            <div v-if="!isLetterQuestion" class="option-image">
              <img v-if="option.image" :src="option.image" :alt="option.text" @error="handleImageError" />
              <div v-else class="emoji-display">{{ getWordEmojiFromText(option.text) }}</div>
            </div>
            <div v-else class="option-letter">
              {{ option.text }}
            </div>
            <div class="option-text">{{ option.text }}</div>
            <div v-if="showAnswer && option.isCorrect" class="correct-mark">✓</div>
          </div>
        </div>

        <!-- 反馈提示 -->
        <div v-if="showFeedback" class="feedback-message" :class="feedbackType">
          <span class="feedback-icon">{{ feedbackType === 'correct' ? '🎉' : '😢' }}</span>
          <span class="feedback-text">{{ feedbackMessage }}</span>
        </div>

        <!-- 下一题按钮 -->
        <button
          v-if="showNextButton"
          class="next-btn"
          @click="nextQuestion"
        >
          {{ currentQuestionIndex < questions.length - 1 ? '下一题' : '查看结果' }}
        </button>
      </div>
    </div>

    <!-- 通关奖励界面 -->
    <div v-if="currentView === 'reward'" class="reward-container">
      <div class="reward-content">
        <div class="reward-animation">
          <div class="confetti"></div>
          <div class="confetti"></div>
          <div class="confetti"></div>
          <div class="confetti"></div>
          <div class="confetti"></div>
        </div>
        <div class="reward-icon">{{ Math.round((correctCount / questions.length) * 100) === 100 ? '🎉' : '💪' }}</div>
        <h2>{{ Math.round((correctCount / questions.length) * 100) === 100 ? '恭喜通关！' : '继续加油！' }}</h2>
        <p class="reward-message">
          {{ Math.round((correctCount / questions.length) * 100) === 100 
            ? `你成功完成了第${currentLevel.level}关` 
            : `第${currentLevel.level}关需要100%正确率才能通过，继续努力吧！` }}
        </p>
        
        <div class="reward-stats">
          <div class="stat-card">
            <div class="stat-label">正确率</div>
            <div class="stat-value">{{ Math.round((correctCount / questions.length) * 100) }}%</div>
          </div>
          <div class="stat-card">
            <div class="stat-label">获得星星</div>
            <div class="stat-value">{{ earnedStars }}⭐</div>
            <div v-if="earnedStarsThisTime > 0" class="stat-detail">本次获得: +{{ earnedStarsThisTime }}⭐</div>
          </div>
        </div>

        <div class="reward-actions">
          <button class="action-btn primary" @click="backToMap">返回地图</button>
          <button v-if="hasNextLevel" class="action-btn secondary" @click="nextLevel">下一关</button>
        </div>
      </div>
    </div>

    <!-- 进度查看界面 -->
    <div v-if="currentView === 'progress'" class="progress-view-container">
      <div class="progress-view-header">
        <h2>📊 学习进度</h2>
        <button class="close-progress-btn" @click="currentView = currentDifficulty ? 'map' : 'difficulty'">×</button>
      </div>
      
      <div class="progress-summary">
        <div class="summary-card">
          <div class="summary-label">总进度</div>
          <div class="summary-value">{{ progressPercentage }}%</div>
          <div class="summary-detail">{{ completedLevels }}/{{ totalLevels }} 关</div>
        </div>
        <div class="summary-card">
          <div class="summary-label">总星星</div>
          <div class="summary-value">{{ totalStars }}⭐</div>
        </div>
        <div class="summary-card">
          <div class="summary-label">通过关卡</div>
          <div class="summary-value">{{ passedLevelsCount }}</div>
        </div>
        <div class="summary-card">
          <div class="summary-label">未通过关卡</div>
          <div class="summary-value">{{ failedLevelsCount }}</div>
        </div>
      </div>
      
      <div class="progress-tabs">
        <button 
          class="tab-btn" 
          :class="{ active: progressTab === 'all' }"
          @click="progressTab = 'all'"
        >
          全部记录
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: progressTab === 'passed' }"
          @click="progressTab = 'passed'"
        >
          通过记录
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: progressTab === 'failed' }"
          @click="progressTab = 'failed'"
        >
          未通过记录
        </button>
      </div>
      
      <div class="progress-records">
        <div 
          v-for="record in filteredProgressRecords" 
          :key="record.id"
          class="progress-record-card"
          :class="{ 'passed': record.passed, 'failed': !record.passed }"
        >
          <div class="record-header">
            <div class="record-info">
              <div class="record-difficulty">{{ record.difficultyName }}</div>
              <div class="record-level">{{ record.levelName }}</div>
            </div>
            <div class="record-status">
              <span v-if="record.passed" class="status-badge passed">✓ 通过</span>
              <span v-else class="status-badge failed">✗ 未通过</span>
            </div>
          </div>
          
          <div class="record-details">
            <div class="record-item">
              <span class="record-label">完成时间：</span>
              <span class="record-value">{{ formatDateTime(record.completeTime) }}</span>
            </div>
            <div class="record-item">
              <span class="record-label">正确率：</span>
              <span class="record-value">{{ record.accuracy }}%</span>
            </div>
            <div class="record-item">
              <span class="record-label">获得星星：</span>
              <span class="record-value">{{ record.stars }}⭐</span>
            </div>
            <div v-if="!record.passed && record.wrongWords && record.wrongWords.length > 0" class="record-item">
              <span class="record-label">错误单词：</span>
              <button class="view-wrong-words-btn" @click="viewWrongWords(record)">
                查看 ({{ record.wrongWords.length }}个)
              </button>
            </div>
          </div>
        </div>
        
        <div v-if="filteredProgressRecords.length === 0" class="empty-records">
          <div class="empty-icon">📝</div>
          <div class="empty-text">暂无{{ progressTab === 'all' ? '' : progressTab === 'passed' ? '通过' : '未通过' }}记录</div>
        </div>
      </div>
    </div>
    
    <!-- 错误单词查看模态框 -->
    <div v-if="showWrongWordsModal" class="wrong-words-modal-overlay" @click="showWrongWordsModal = false">
      <div class="wrong-words-modal" @click.stop>
        <div class="modal-header">
          <h3>错误单词详情</h3>
          <button class="close-modal-btn" @click="showWrongWordsModal = false">×</button>
        </div>
        <div class="modal-content">
          <div class="wrong-words-info">
            <div class="info-item">
              <span class="info-label">关卡：</span>
              <span class="info-value">{{ currentWrongWordsRecord?.levelName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">完成时间：</span>
              <span class="info-value">{{ formatDateTime(currentWrongWordsRecord?.completeTime) }}</span>
            </div>
          </div>
          <div class="wrong-words-list">
            <div 
              v-for="(word, index) in currentWrongWordsRecord?.wrongWords" 
              :key="index"
              class="wrong-word-item"
            >
              <div class="word-display-item">
                <div class="word-en">{{ word.word }}</div>
                <div class="word-cn">{{ word.chinese }}</div>
                <div class="word-phonetic">/{{ word.phonetic }}/</div>
              </div>
              <button class="play-word-btn" @click="playWordSound(word.word)">
                🔊 播放发音
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 排行榜界面 -->
    <div v-if="currentView === 'leaderboard'" class="leaderboard-container">
      <div class="leaderboard-header">
        <h2>🏆 星星积分排行榜</h2>
        <button class="close-leaderboard-btn" @click="currentView = currentDifficulty ? 'map' : 'difficulty'">×</button>
      </div>
      
      <div class="leaderboard-tabs">
        <button 
          class="tab-btn" 
          :class="{ active: leaderboardTab === 'class' }"
          @click="leaderboardTab = 'class'; loadLeaderboard()"
        >
          本班级排名
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: leaderboardTab === 'all' }"
          @click="leaderboardTab = 'all'; loadLeaderboard()"
        >
          全部排名
        </button>
      </div>
      
      <div v-if="loadingLeaderboard" class="loading-indicator">
        <div class="spinner"></div>
        <div>加载中...</div>
      </div>
      
      <div v-else class="leaderboard-content">
        <div class="ranking-list">
          <div 
            v-for="(student, index) in currentRanking" 
            :key="student.id || index"
            class="ranking-item"
            :class="{
              'rank-1': index === 0,
              'rank-2': index === 1,
              'rank-3': index === 2,
              'current-student': currentStudent && student.id === currentStudent.id
            }"
          >
            <div class="rank-number">
              <span v-if="index < 3" class="medal">
                {{ index === 0 ? '🥇' : index === 1 ? '🥈' : '🥉' }}
              </span>
              <span v-else class="rank-text">{{ index + 1 }}</span>
            </div>
            <div class="student-info">
              <div class="student-name">{{ student.name || student.username || '未知' }}</div>
              <div v-if="student.className" class="student-class">{{ student.className }}</div>
            </div>
            <div class="student-stars">
              <span class="stars-icon">⭐</span>
              <span class="stars-value">{{ student.totalStars || 0 }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="currentRanking.length === 0" class="empty-leaderboard">
          <div class="empty-icon">📊</div>
          <div class="empty-text">暂无排名数据</div>
        </div>
      </div>
    </div>

    <!-- 成就墙界面 -->
    <div v-if="currentView === 'achievements'" class="achievements-container">
      <div class="achievements-header">
        <h2>🏆 我的成就</h2>
        <button class="close-achievements-btn" @click="currentView = 'map'">×</button>
      </div>
      <div class="achievements-grid">
        <div
          v-for="achievement in achievements"
          :key="achievement.id"
          class="achievement-card"
          :class="{ 'unlocked': achievement.unlocked }"
        >
          <div class="achievement-icon">{{ achievement.icon }}</div>
          <div class="achievement-name">{{ achievement.name }}</div>
          <div class="achievement-desc">{{ achievement.description }}</div>
          <div v-if="achievement.unlocked" class="achievement-date">
            获得时间: {{ achievement.unlockDate }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { childEnglishApi } from '@/api/childEnglishApi';
import { userService } from '@/services/userService';

export default {
  name: 'GameLearning',
  data() {
    return {
      currentView: 'difficulty', // difficulty, map, game, reward, achievements, progress, leaderboard
      currentDifficulty: null, // 'easy', 'medium', 'hard'
      currentDifficultyName: '',
      progressTab: 'all', // all, passed, failed
      showWrongWordsModal: false,
      currentWrongWordsRecord: null,
      wrongWords: [], // 当前关卡的错误单词列表
      earnedStarsThisTime: 0, // 本次获得的星星积分
      leaderboardTab: 'class', // class, all
      classRanking: [], // 本班级排名
      allRanking: [], // 全部排名
      currentStudent: null, // 当前学生信息
      loadingLeaderboard: false,
      difficulties: [
        {
          value: 'easy',
          name: '简单',
          icon: '🌱',
          description: '24字母 + 生活中常见物（水果等）',
          levelCount: 20
        },
        {
          value: 'medium',
          name: '中等',
          icon: '📚',
          description: '小学生必掌握单词',
          levelCount: 25
        },
        {
          value: 'hard',
          name: '困难',
          icon: '🎓',
          description: '初中生必掌握单词',
          levelCount: 30
        }
      ],
      gameLevels: [],
      currentLevel: null,
      currentQuestionIndex: 0,
      questions: [],
      selectedAnswer: null,
      showAnswer: false,
      showFeedback: false,
      feedbackType: '',
      feedbackMessage: '',
      showNextButton: false,
      correctCount: 0,
      earnedStars: 0,
      totalStars: 0,
      completedLevels: 0,
      totalLevels: 75, // 所有模式关卡总和：20+25+30=75
      scrollOffset: 0,
      maxScrollOffset: 0,
      achievements: [
        {
          id: 1,
          name: '初出茅庐',
          description: '完成第一关',
          icon: '🌱',
          unlocked: false,
          unlockDate: ''
        },
        {
          id: 2,
          name: '单词小达人',
          description: '连续答对10题',
          icon: '⭐',
          unlocked: false,
          unlockDate: ''
        },
        {
          id: 3,
          name: '完美通关',
          description: '单关正确率100%',
          icon: '💯',
          unlocked: false,
          unlockDate: ''
        },
        {
          id: 4,
          name: '坚持不懈',
          description: '完成所有关卡',
          icon: '🏆',
          unlocked: false,
          unlockDate: ''
        }
      ]
    };
  },
  computed: {
    currentQuestion() {
      return this.questions[this.currentQuestionIndex] || {};
    },
    hasNextLevel() {
      if (!this.currentLevel) return false;
      const nextLevel = this.gameLevels.find(l => l.level === this.currentLevel.level + 1);
      return nextLevel && nextLevel.unlocked;
    },
    progressPercentage() {
      if (this.totalLevels === 0) return 0;
      return Math.round((this.completedLevels / this.totalLevels) * 100);
    },
    progressRecords() {
      // 从localStorage读取所有进度记录
      const records = [];
      const difficulties = ['easy', 'medium', 'hard'];
      const difficultyNames = { 'easy': '简单', 'medium': '中等', 'hard': '困难' };
      
      difficulties.forEach(difficulty => {
        const key = `game_progress_${difficulty}`;
        const progress = JSON.parse(localStorage.getItem(key) || '{}');
        
        // 遍历所有关卡记录
        Object.keys(progress).forEach(levelKey => {
          if (levelKey.startsWith('level_')) {
            const levelData = progress[levelKey];
            if (levelData.completeTime) {
              const levelNum = parseInt(levelKey.replace('level_', ''));
              
              // 兼容旧数据：如果没有passed字段，根据准确率推断
              let passed = levelData.passed;
              if (passed === undefined) {
                // 旧数据：100%算通过，其他算未通过
                const accuracy = levelData.accuracy || 0;
                passed = (accuracy === 100);
                // 更新旧数据，添加passed字段
                levelData.passed = passed;
                progress[levelKey] = levelData;
                localStorage.setItem(key, JSON.stringify(progress));
              } else {
                passed = (passed === true);
              }
              
              // 兼容旧数据：获取本次获得的星星积分
              let earnedStars = levelData.earnedStarsThisTime;
              if (earnedStars === undefined) {
                // 旧数据：根据准确率和是否通过推断本次获得的星星
                const accuracy = levelData.accuracy || 0;
                if (accuracy === 100) {
                  // 100%可能是3个（一次性通过）或1个（分次通过）
                  // 检查是否有bestAccuracy字段，如果没有说明可能是第一次
                  if (levelData.bestAccuracy === undefined && levelData.completed) {
                    earnedStars = 3; // 假设是一次性通过
                  } else if (levelData.bestAccuracy < 100) {
                    earnedStars = 1; // 从非100%提升到100%，获得1个
                  } else {
                    earnedStars = 1; // 保守估计，给1个
                  }
                } else if (accuracy >= 75) {
                  earnedStars = 1; // 75%获得1个
                } else {
                  earnedStars = 0;
                }
                // 更新旧数据，添加earnedStarsThisTime字段
                levelData.earnedStarsThisTime = earnedStars;
                progress[levelKey] = levelData;
                localStorage.setItem(key, JSON.stringify(progress));
              }
              
              records.push({
                id: `${difficulty}_${levelNum}`,
                difficulty: difficulty,
                difficultyName: difficultyNames[difficulty],
                level: levelNum,
                levelName: this.getLevelName(difficulty, levelNum),
                passed: passed,
                accuracy: levelData.accuracy || 0,
                stars: earnedStars, // 显示本次获得的星星积分
                displayStars: levelData.stars || 0, // 显示星星数（用于地图）
                completeTime: levelData.completeTime,
                wrongWords: levelData.wrongWords || []
              });
            }
          }
        });
      });
      
      // 按完成时间倒序排列
      return records.sort((a, b) => new Date(b.completeTime) - new Date(a.completeTime));
    },
    filteredProgressRecords() {
      if (this.progressTab === 'all') {
        return this.progressRecords;
      } else if (this.progressTab === 'passed') {
        return this.progressRecords.filter(r => r.passed);
      } else {
        return this.progressRecords.filter(r => !r.passed);
      }
    },
    passedLevelsCount() {
      return this.progressRecords.filter(r => r.passed).length;
    },
    failedLevelsCount() {
      return this.progressRecords.filter(r => !r.passed).length;
    },
    isLetterQuestion() {
      // 判断是否是字母题目（简单模式的前6关）
      return this.currentDifficulty === 'easy' && 
             this.currentLevel && 
             this.currentLevel.level <= 6;
    },
    currentRanking() {
      return this.leaderboardTab === 'class' ? this.classRanking : this.allRanking;
    }
  },
  async mounted() {
    // 不再自动加载关卡，等待用户选择难度
    window.addEventListener('resize', this.updateMaxScrollOffset);
    // 迁移旧数据
    this.migrateAllOldData();
    // 加载所有难度的进度统计
    this.updateAllProgress();
    
    // 初始化语音合成（预热，减少首次播放延迟）
    if ('speechSynthesis' in window) {
      // 创建一个空的utterance来预热语音引擎
      const warmupUtterance = new SpeechSynthesisUtterance('');
      warmupUtterance.volume = 0;
      window.speechSynthesis.speak(warmupUtterance);
      window.speechSynthesis.cancel();
    }
  },
  
  beforeUnmount() {
    // 清理：停止所有播放
    if (window.speechSynthesis) {
      window.speechSynthesis.cancel();
    }
    if (this.playSoundTimeout) {
      clearTimeout(this.playSoundTimeout);
    }
    window.removeEventListener('resize', this.updateMaxScrollOffset);
  },
  methods: {
    selectDifficulty(difficulty) {
      this.currentDifficulty = difficulty;
      const selected = this.difficulties.find(d => d.value === difficulty);
      this.currentDifficultyName = selected ? selected.name : '';
      this.loadGameLevels();
      this.currentView = 'map';
    },
    
    backToDifficulty() {
      this.currentView = 'difficulty';
      this.currentDifficulty = null;
      this.currentDifficultyName = '';
      this.gameLevels = [];
    },
    
    migrateAllOldData() {
      // 迁移所有旧数据，确保所有关卡都有totalStars字段
      const difficulties = ['easy', 'medium', 'hard'];
      let migrated = false;
      
      difficulties.forEach(difficulty => {
        const key = `game_progress_${difficulty}`;
        const progress = JSON.parse(localStorage.getItem(key) || '{}');
        let needUpdate = false;
        
        Object.keys(progress).forEach(levelKey => {
          if (levelKey.startsWith('level_')) {
            const levelData = progress[levelKey];
            // 如果有记录但没有totalStars字段，需要迁移
            if (levelData.completeTime && levelData.totalStars === undefined) {
              const migratedStars = this.migrateOldStars(levelData);
              levelData.totalStars = migratedStars;
              progress[levelKey] = levelData;
              needUpdate = true;
              migrated = true;
            }
          }
        });
        
        if (needUpdate) {
          localStorage.setItem(key, JSON.stringify(progress));
        }
      });
      
      if (migrated) {
        console.log('数据迁移完成：已迁移旧版星星积分数据');
      }
    },
    
    migrateOldStars(levelData) {
      // 迁移旧数据的星星积分
      // 旧版本可能直接用stars存储星星数，需要根据准确率推断应该获得的积分
      if (levelData.totalStars !== undefined) {
        return levelData.totalStars;
      }
      
      // 如果有准确率信息，根据准确率推断
      if (levelData.accuracy !== undefined) {
        const accuracy = levelData.accuracy;
        if (accuracy === 100) {
          // 100%可能是3个星星（一次性通过）或2个星星（分次通过）
          // 如果completed为true且是第一次，可能是3个，否则可能是2个
          if (levelData.completed && levelData.isFirstAttempt !== false) {
            return 3; // 假设是一次性通过
          } else {
            return 2; // 分次通过，最多2个
          }
        } else if (accuracy >= 75) {
          return 1; // 75%获得1个星星
        }
      }
      
      // 如果只有stars字段，尝试推断
      if (levelData.stars !== undefined) {
        // 旧版本可能用stars表示显示星星数，需要转换为积分
        // 3颗星可能是3个积分（一次性通过）或2个积分（分次通过）
        // 2颗星是1个积分（75%）
        // 1颗星是0个积分
        if (levelData.stars === 3) {
          // 假设是分次通过的，给2个积分（保守估计）
          return 2;
        } else if (levelData.stars === 2) {
          return 1;
        } else {
          return 0;
        }
      }
      
      return 0;
    },
    
    getCompletedCountByDifficulty(difficulty) {
      // 从localStorage获取已完成关卡数
      const key = `game_progress_${difficulty}`;
      const progress = JSON.parse(localStorage.getItem(key) || '{}');
      return progress.completedCount || 0;
    },
    
    updateAllProgress() {
      // 计算所有难度的总完成关卡数
      let totalCompleted = 0;
      const difficulties = ['easy', 'medium', 'hard'];
      
      difficulties.forEach(difficulty => {
        const key = `game_progress_${difficulty}`;
        const progress = JSON.parse(localStorage.getItem(key) || '{}');
        totalCompleted += progress.completedCount || 0;
      });
      
      this.completedLevels = totalCompleted;
      this.totalLevels = 75; // 固定为所有模式关卡总和
      
      // 计算总星星积分（使用totalStars，不是显示星星数）
      let totalStarsCount = 0;
      difficulties.forEach(difficulty => {
        const key = `game_progress_${difficulty}`;
        const progress = JSON.parse(localStorage.getItem(key) || '{}');
        // 遍历所有关卡，累加星星积分
        Object.keys(progress).forEach(levelKey => {
          if (levelKey.startsWith('level_')) {
            const levelData = progress[levelKey];
            // 兼容旧数据：如果有totalStars就用totalStars，否则尝试从stars迁移
            if (levelData.totalStars !== undefined) {
              totalStarsCount += levelData.totalStars;
            } else if (levelData.stars !== undefined && levelData.stars > 0) {
              // 旧数据迁移：将stars作为totalStars（兼容旧版本）
              // 但需要根据准确率判断实际应该获得的星星积分
              const migratedStars = this.migrateOldStars(levelData);
              totalStarsCount += migratedStars;
              // 更新数据，添加totalStars字段
              levelData.totalStars = migratedStars;
              progress[levelKey] = levelData;
              localStorage.setItem(key, JSON.stringify(progress));
            }
          }
        });
      });
      this.totalStars = totalStarsCount;
    },
    
    scrollLeft() {
      const scrollAmount = 400; // 每次滚动距离
      this.scrollOffset = Math.min(0, this.scrollOffset + scrollAmount);
    },
    
    scrollRight() {
      const scrollAmount = 400; // 每次滚动距离
      this.scrollOffset = Math.max(this.maxScrollOffset, this.scrollOffset - scrollAmount);
    },
    
    updateMaxScrollOffset() {
      this.$nextTick(() => {
        const container = this.$refs.scrollContainer;
        if (container) {
          const containerWidth = container.offsetWidth;
          const levelsContainer = container.querySelector('.levels-container');
          if (levelsContainer) {
            const contentWidth = levelsContainer.scrollWidth;
            const maxOffset = -(contentWidth - containerWidth);
            this.maxScrollOffset = maxOffset;
            // 确保当前滚动位置在有效范围内
            if (this.scrollOffset < maxOffset) {
              this.scrollOffset = maxOffset;
            }
            if (this.scrollOffset > 0) {
              this.scrollOffset = 0;
            }
          }
        }
      });
    },
    
    async loadGameLevels() {
      if (!this.currentDifficulty) {
        return;
      }
      
      try {
        const response = await childEnglishApi.getGameLevels(this.currentDifficulty);
        if (response.code === 200 && response.data) {
          // 处理关卡数据
          const levels = response.data.levels || [];
          const progressKey = `game_progress_${this.currentDifficulty}`;
          const progress = JSON.parse(localStorage.getItem(progressKey) || '{}');
          
          this.gameLevels = levels.map((level, index) => {
            const levelProgress = progress[`level_${level.level}`] || {};
            // 检查上一关是否完成，如果完成则解锁当前关
            let unlocked = index === 0; // 第一关默认解锁
            if (index > 0) {
              const prevLevel = levels[index - 1];
              const prevLevelProgress = progress[`level_${prevLevel.level}`] || {};
              // 只有100%完成的关卡才能解锁下一关
              unlocked = prevLevelProgress.completed === true || false;
            }
            
            return {
              id: level.level || index + 1,
              level: level.level || index + 1,
              name: level.name || `关卡${index + 1}`,
              completed: levelProgress.completed || false, // 只有100%才算completed
              attempted: levelProgress.attempted || false, // 是否闯过
              stars: levelProgress.stars || 0, // 显示星星数
              bestAccuracy: levelProgress.bestAccuracy || 0, // 历史最高准确率
              unlocked: unlocked,
              icon: this.getLevelIcon(index + 1),
              theme: level.theme || '基础单词',
              taskType: level.taskType || '图片选择',
              knowledgeTags: level.knowledgeTags || [],
              passCondition: level.passCondition || '准确率=100%'
            };
          });
          
          // 不更新totalLevels，保持为75（所有模式总和）
          // 更新当前难度的完成数，但总完成数需要从所有难度统计
          this.updateAllProgress();
          this.updateMaxScrollOffset();
        } else {
          // 使用模拟数据
          this.initMockLevels();
        }
      } catch (error) {
        console.error('加载关卡失败:', error);
        this.initMockLevels();
      }
    },
    
    initMockLevels() {
      if (!this.currentDifficulty) {
        return;
      }
      
      // 根据难度生成不同关卡
      const levelConfigs = this.getLevelConfigsByDifficulty();
      const progressKey = `game_progress_${this.currentDifficulty}`;
      const progress = JSON.parse(localStorage.getItem(progressKey) || '{}');
      
      this.gameLevels = levelConfigs.map((config, index) => {
        const levelProgress = progress[`level_${index + 1}`] || {};
        // 检查上一关是否完成，如果完成则解锁当前关
        let unlocked = index === 0; // 第一关默认解锁
        if (index > 0) {
          const prevLevelProgress = progress[`level_${index}`] || {};
          // 只有100%完成的关卡才能解锁下一关
          unlocked = prevLevelProgress.completed === true || false;
        }
        
        return {
          id: index + 1,
          level: index + 1,
          name: config.name,
          completed: levelProgress.completed || false, // 只有100%才算completed
          attempted: levelProgress.attempted || false, // 是否闯过
          stars: levelProgress.stars || 0, // 显示星星数
          bestAccuracy: levelProgress.bestAccuracy || 0, // 历史最高准确率
          unlocked: unlocked,
          icon: config.icon,
          theme: config.theme,
          taskType: '图片选择',
          knowledgeTags: config.tags || [],
          passCondition: '准确率≥80%'
        };
      });
      
      // 不更新totalLevels，保持为75（所有模式总和）
      // 更新当前难度的完成数，但总完成数需要从所有难度统计
      this.updateAllProgress();
      this.updateMaxScrollOffset();
    },
    
    getLevelConfigsByDifficulty() {
      if (this.currentDifficulty === 'easy') {
        // 简单模式：24字母 + 常见物（20关）
        const levels = [];
        // 字母关卡（6关，每关4个字母）
        const letterGroups = [
          { name: '字母A-D', letters: ['A', 'B', 'C', 'D'] },
          { name: '字母E-H', letters: ['E', 'F', 'G', 'H'] },
          { name: '字母I-L', letters: ['I', 'J', 'K', 'L'] },
          { name: '字母M-P', letters: ['M', 'N', 'O', 'P'] },
          { name: '字母Q-T', letters: ['Q', 'R', 'S', 'T'] },
          { name: '字母U-X', letters: ['U', 'V', 'W', 'X'] }
        ];
        letterGroups.forEach(group => {
          levels.push({ name: group.name, icon: '🔤', theme: '字母认知', tags: ['字母'] });
        });
        
        // 常见物关卡（14关）
        const commonObjects = [
          { name: '水果乐园', icon: '🍎', theme: '常见物', tags: ['水果'] },
          { name: '日常用品', icon: '🏠', theme: '常见物', tags: ['日常'] },
          { name: '动物朋友', icon: '🐾', theme: '常见物', tags: ['动物'] },
          { name: '交通工具', icon: '🚗', theme: '常见物', tags: ['交通'] },
          { name: '身体部位', icon: '👤', theme: '常见物', tags: ['身体'] },
          { name: '颜色世界', icon: '🎨', theme: '常见物', tags: ['颜色'] },
          { name: '数字王国', icon: '🔢', theme: '常见物', tags: ['数字'] },
          { name: '食物天地', icon: '🍔', theme: '常见物', tags: ['食物'] },
          { name: '学校用品', icon: '🎒', theme: '常见物', tags: ['学校'] },
          { name: '家庭成员', icon: '👨‍👩‍👧‍👦', theme: '常见物', tags: ['家庭'] },
          { name: '自然景观', icon: '🌳', theme: '常见物', tags: ['自然'] },
          { name: '天气变化', icon: '☀️', theme: '常见物', tags: ['天气'] },
          { name: '动作词汇', icon: '🏃', theme: '常见物', tags: ['动作'] },
          { name: '综合练习', icon: '⭐', theme: '常见物', tags: ['综合'] }
        ];
        commonObjects.forEach(obj => {
          levels.push(obj);
        });
        
        return levels;
      } else if (this.currentDifficulty === 'medium') {
        // 中等模式：小学生必掌握单词（25关）
        const themes = [
          { name: '基础单词1', icon: '📚', tags: ['基础'] },
          { name: '基础单词2', icon: '📚', tags: ['基础'] },
          { name: '基础单词3', icon: '📚', tags: ['基础'] },
          { name: '动物世界', icon: '🐾', tags: ['动物'] },
          { name: '动物朋友', icon: '🐱', tags: ['动物'] },
          { name: '颜色认知', icon: '🎨', tags: ['颜色'] },
          { name: '多彩世界', icon: '🌈', tags: ['颜色'] },
          { name: '数字学习', icon: '🔢', tags: ['数字'] },
          { name: '数字应用', icon: '🔟', tags: ['数字'] },
          { name: '身体部位', icon: '👤', tags: ['身体'] },
          { name: '身体认知', icon: '👁️', tags: ['身体'] },
          { name: '家庭成员', icon: '👨‍👩‍👧‍👦', tags: ['家庭'] },
          { name: '家庭关系', icon: '👪', tags: ['家庭'] },
          { name: '学校用品', icon: '🎒', tags: ['学校'] },
          { name: '校园生活', icon: '🏫', tags: ['学校'] },
          { name: '食物单词', icon: '🍔', tags: ['食物'] },
          { name: '美味食物', icon: '🍕', tags: ['食物'] },
          { name: '动作单词', icon: '🏃', tags: ['动作'] },
          { name: '日常动作', icon: '🚶', tags: ['动作'] },
          { name: '时间表达', icon: '⏰', tags: ['时间'] },
          { name: '星期月份', icon: '📅', tags: ['时间'] },
          { name: '天气词汇', icon: '☀️', tags: ['天气'] },
          { name: '季节变化', icon: '🍂', tags: ['季节'] },
          { name: '形状认知', icon: '🔷', tags: ['形状'] },
          { name: '综合测试', icon: '🏆', tags: ['综合'] }
        ];
        return themes.map(t => ({ ...t, theme: '小学单词' }));
      } else {
        // 困难模式：初中生必掌握单词（30关）
        const themes = [
          { name: '初中基础1', icon: '🎓', tags: ['基础'] },
          { name: '初中基础2', icon: '🎓', tags: ['基础'] },
          { name: '初中基础3', icon: '🎓', tags: ['基础'] },
          { name: '学科词汇', icon: '📖', tags: ['学科'] },
          { name: '数学词汇', icon: '➕', tags: ['学科'] },
          { name: '科学词汇', icon: '🔬', tags: ['学科'] },
          { name: '情感表达', icon: '😊', tags: ['情感'] },
          { name: '情绪词汇', icon: '😢', tags: ['情感'] },
          { name: '时间表达', icon: '⏰', tags: ['时间'] },
          { name: '时间管理', icon: '⏳', tags: ['时间'] },
          { name: '天气词汇', icon: '☀️', tags: ['天气'] },
          { name: '气候环境', icon: '🌍', tags: ['环境'] },
          { name: '运动项目', icon: '⚽', tags: ['运动'] },
          { name: '体育运动', icon: '🏀', tags: ['运动'] },
          { name: '交通工具', icon: '🚗', tags: ['交通'] },
          { name: '出行方式', icon: '✈️', tags: ['交通'] },
          { name: '职业词汇', icon: '👔', tags: ['职业'] },
          { name: '工作职业', icon: '👨‍💼', tags: ['职业'] },
          { name: '形容词1', icon: '✨', tags: ['形容词'] },
          { name: '形容词2', icon: '💎', tags: ['形容词'] },
          { name: '动词短语1', icon: '💫', tags: ['动词'] },
          { name: '动词短语2', icon: '🌟', tags: ['动词'] },
          { name: '名词词汇', icon: '📝', tags: ['名词'] },
          { name: '副词应用', icon: '🔤', tags: ['副词'] },
          { name: '介词用法', icon: '📍', tags: ['介词'] },
          { name: '连词连接', icon: '🔗', tags: ['连词'] },
          { name: '日常对话', icon: '💬', tags: ['对话'] },
          { name: '情景交际', icon: '🗣️', tags: ['交际'] },
          { name: '阅读理解', icon: '📖', tags: ['阅读'] },
          { name: '综合测试', icon: '🏆', tags: ['综合'] }
        ];
        return themes.map(t => ({ ...t, theme: '初中单词' }));
      }
    },
    
    getLevelIcon(levelNum) {
      const icons = ['🔤', '🔗', '📝', '🐾', '🍎', '🚗', '🏠', '👕', '🎨', '🎵'];
      return icons[(levelNum - 1) % icons.length];
    },
    
    selectLevel(level) {
      if (!level.unlocked) {
        alert('该关卡尚未解锁，请先完成前面的关卡！');
        return;
      }
      
      this.currentLevel = level;
      this.initGameQuestions();
      this.currentView = 'game';
    },
    
    initGameQuestions() {
      // 根据难度和关卡生成题目
      this.questions = this.generateQuestionsByLevel(this.currentDifficulty, this.currentLevel.level);
      this.currentQuestionIndex = 0;
      this.selectedAnswer = null;
      this.showAnswer = false;
      this.showFeedback = false;
      this.showNextButton = false;
      this.correctCount = 0;
      this.wrongWords = []; // 重置错误单词列表
    },
    
    generateQuestionsByLevel(difficulty, level) {
      if (difficulty === 'easy') {
        return this.generateEasyQuestions(level);
      } else if (difficulty === 'medium') {
        return this.generateMediumQuestions(level);
      } else {
        return this.generateHardQuestions(level);
      }
    },
    
    generateEasyQuestions(level) {
      // 简单模式：24字母 + 常见物（20关）
      if (level <= 6) {
        // 字母关卡（1-6关）
        const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        const startIndex = (level - 1) * 4;
        const levelLetters = letters.slice(startIndex, startIndex + 4);
        
        return levelLetters.map(letter => ({
          word: letter,
          chinese: null, // 字母不显示中文意思
          phonetic: null, // 字母不显示音标
          examples: [], // 字母不显示例句
          options: this.generateLetterOptions(letter)
        }));
      } else {
        // 常见物关卡（7-20关）
        const wordSets = {
          7: ['Apple', 'Banana', 'Orange', 'Grape'], // 水果乐园
          8: ['Book', 'Pen', 'Table', 'Chair'], // 日常用品
          9: ['Cat', 'Dog', 'Bird', 'Fish'], // 动物朋友
          10: ['Car', 'Bus', 'Bike', 'Train'], // 交通工具
          11: ['Head', 'Hand', 'Foot', 'Eye'], // 身体部位
          12: ['Red', 'Blue', 'Green', 'Yellow'], // 颜色世界
          13: ['One', 'Two', 'Three', 'Four'], // 数字王国
          14: ['Bread', 'Milk', 'Egg', 'Rice'], // 食物天地
          15: ['School', 'Teacher', 'Student', 'Class'], // 学校用品
          16: ['Father', 'Mother', 'Brother', 'Sister'], // 家庭成员
          17: ['Sun', 'Moon', 'Star', 'Cloud'], // 自然景观
          18: ['Sunny', 'Rainy', 'Cloudy', 'Windy'], // 天气变化
          19: ['Run', 'Jump', 'Walk', 'Sit'], // 动作词汇
          20: ['Apple', 'Cat', 'Book', 'Red'] // 综合练习
        };
        
        const words = wordSets[level] || wordSets[7];
        return words.map(word => ({
          word: word,
          chinese: this.getChineseTranslation(word), // 单词显示中文意思
          phonetic: this.getPhonetic(word), // 获取音标
          examples: this.getExamples(word), // 获取例句
          options: this.generateWordOptions(word, this.getChineseTranslation(word), this.getRandomWords(words, word))
        }));
      }
    },
    
    generateMediumQuestions(level) {
      // 中等模式：小学生必掌握单词（25关）
      const wordSets = {
        1: ['Cat', 'Dog', 'Bird', 'Fish'],
        2: ['Sun', 'Moon', 'Star', 'Cloud'],
        3: ['Lion', 'Tiger', 'Elephant', 'Monkey'],
        4: ['Red', 'Blue', 'Green', 'Yellow'],
        5: ['Pink', 'Purple', 'Orange', 'Brown'],
        6: ['One', 'Two', 'Three', 'Four'],
        7: ['Five', 'Six', 'Seven', 'Eight'],
        8: ['Head', 'Hand', 'Foot', 'Eye'],
        9: ['Nose', 'Mouth', 'Ear', 'Leg'],
        10: ['Father', 'Mother', 'Brother', 'Sister'],
        11: ['Grandpa', 'Grandma', 'Uncle', 'Aunt'],
        12: ['School', 'Teacher', 'Student', 'Class'],
        13: ['Desk', 'Chair', 'Blackboard', 'Book'],
        14: ['Bread', 'Milk', 'Egg', 'Rice'],
        15: ['Apple', 'Banana', 'Orange', 'Grape'],
        16: ['Run', 'Jump', 'Walk', 'Sit'],
        17: ['Stand', 'Sleep', 'Eat', 'Drink'],
        18: ['Monday', 'Tuesday', 'Wednesday', 'Thursday'],
        19: ['Friday', 'Saturday', 'Sunday', 'Week'],
        20: ['Sunny', 'Rainy', 'Cloudy', 'Windy'],
        21: ['Spring', 'Summer', 'Autumn', 'Winter'],
        22: ['Circle', 'Square', 'Triangle', 'Rectangle'],
        23: ['Big', 'Small', 'Tall', 'Short'],
        24: ['Happy', 'Sad', 'Angry', 'Excited'],
        25: ['Cat', 'Red', 'One', 'Run'] // 综合测试
      };
      
      const words = wordSets[level] || wordSets[1];
      return words.map(word => ({
        word: word,
        chinese: this.getChineseTranslation(word), // 单词显示中文意思
        phonetic: this.getPhonetic(word), // 获取音标
        examples: this.getExamples(word), // 获取例句
        options: this.generateWordOptions(word, this.getChineseTranslation(word), this.getRandomWords(words, word))
      }));
    },
    
    generateHardQuestions(level) {
      // 困难模式：初中生必掌握单词（30关）
      const wordSets = {
        1: ['Beautiful', 'Wonderful', 'Excellent', 'Perfect'],
        2: ['Amazing', 'Fantastic', 'Brilliant', 'Outstanding'],
        3: ['Mathematics', 'Science', 'History', 'Geography'],
        4: ['Physics', 'Chemistry', 'Biology', 'English'],
        5: ['Happy', 'Sad', 'Angry', 'Excited'],
        6: ['Worried', 'Surprised', 'Disappointed', 'Proud'],
        7: ['Morning', 'Afternoon', 'Evening', 'Night'],
        8: ['Today', 'Tomorrow', 'Yesterday', 'Weekend'],
        9: ['Sunny', 'Rainy', 'Cloudy', 'Windy'],
        10: ['Environment', 'Pollution', 'Protect', 'Nature'],
        11: ['Football', 'Basketball', 'Tennis', 'Swimming'],
        12: ['Volleyball', 'Baseball', 'Soccer', 'Badminton'],
        13: ['Car', 'Bus', 'Train', 'Airplane'],
        14: ['Ship', 'Bicycle', 'Motorcycle', 'Subway'],
        15: ['Doctor', 'Teacher', 'Engineer', 'Artist'],
        16: ['Nurse', 'Lawyer', 'Pilot', 'Chef'],
        17: ['Big', 'Small', 'Tall', 'Short'],
        18: ['Wide', 'Narrow', 'Thick', 'Thin'],
        19: ['Study', 'Learn', 'Practice', 'Improve'],
        20: ['Review', 'Memorize', 'Understand', 'Master'],
        21: ['Important', 'Necessary', 'Useful', 'Valuable'],
        22: ['Essential', 'Significant', 'Critical', 'Crucial'],
        23: ['Challenge', 'Opportunity', 'Success', 'Achievement'],
        24: ['Difficult', 'Easy', 'Simple', 'Complex'],
        25: ['Quickly', 'Slowly', 'Carefully', 'Suddenly'],
        26: ['In', 'On', 'At', 'By'],
        27: ['And', 'But', 'Or', 'So'],
        28: ['Hello', 'Thanks', 'Sorry', 'Please'],
        29: ['Question', 'Answer', 'Problem', 'Solution'],
        30: ['Beautiful', 'Mathematics', 'Happy', 'Challenge'] // 综合测试
      };
      
      const words = wordSets[level] || wordSets[1];
      return words.map(word => ({
        word: word,
        chinese: this.getChineseTranslation(word), // 单词显示中文意思
        phonetic: this.getPhonetic(word), // 获取音标
        examples: this.getExamples(word), // 获取例句
        options: this.generateWordOptions(word, this.getChineseTranslation(word), this.getRandomWords(words, word))
      }));
    },
    
    getPhonetic(word) {
      // 单词音标映射
      const phoneticMap = {
        'Apple': 'æpl', 'Banana': 'bəˈnænə', 'Orange': 'ˈɔːrɪndʒ', 'Grape': 'ɡreɪp',
        'Book': 'bʊk', 'Pen': 'pen', 'Table': 'ˈteɪbl', 'Chair': 'tʃer',
        'Cat': 'kæt', 'Dog': 'dɔːɡ', 'Bird': 'bɜːrd', 'Fish': 'fɪʃ',
        'Car': 'kɑːr', 'Bus': 'bʌs', 'Bike': 'baɪk', 'Train': 'treɪn',
        'Head': 'hed', 'Hand': 'hænd', 'Foot': 'fʊt', 'Eye': 'aɪ',
        'Red': 'red', 'Blue': 'bluː', 'Green': 'ɡriːn', 'Yellow': 'ˈjeloʊ',
        'One': 'wʌn', 'Two': 'tuː', 'Three': 'θriː', 'Four': 'fɔːr',
        'Bread': 'bred', 'Milk': 'mɪlk', 'Egg': 'eɡ', 'Rice': 'raɪs',
        'School': 'skuːl', 'Teacher': 'ˈtiːtʃər', 'Student': 'ˈstuːdnt', 'Class': 'klæs',
        'Father': 'ˈfɑːðər', 'Mother': 'ˈmʌðər', 'Brother': 'ˈbrʌðər', 'Sister': 'ˈsɪstər',
        'Sun': 'sʌn', 'Moon': 'muːn', 'Star': 'stɑːr', 'Cloud': 'klaʊd',
        'Sunny': 'ˈsʌni', 'Rainy': 'ˈreɪni', 'Cloudy': 'ˈklaʊdi', 'Windy': 'ˈwɪndi',
        'Run': 'rʌn', 'Jump': 'dʒʌmp', 'Walk': 'wɔːk', 'Sit': 'sɪt',
        'Lion': 'ˈlaɪən', 'Tiger': 'ˈtaɪɡər', 'Elephant': 'ˈelɪfənt', 'Monkey': 'ˈmʌŋki',
        'Pink': 'pɪŋk', 'Purple': 'ˈpɜːrpl', 'Brown': 'braʊn',
        'Five': 'faɪv', 'Six': 'sɪks', 'Seven': 'ˈsevn', 'Eight': 'eɪt',
        'Nose': 'noʊz', 'Mouth': 'maʊθ', 'Ear': 'ɪr', 'Leg': 'leɡ',
        'Grandpa': 'ˈɡrænpɑː', 'Grandma': 'ˈɡrænmɑː', 'Uncle': 'ˈʌŋkl', 'Aunt': 'ænt',
        'Desk': 'desk', 'Blackboard': 'ˈblækbɔːrd',
        'Stand': 'stænd', 'Sleep': 'sliːp', 'Eat': 'iːt', 'Drink': 'drɪŋk',
        'Monday': 'ˈmʌndeɪ', 'Tuesday': 'ˈtuːzdeɪ', 'Wednesday': 'ˈwenzdeɪ', 'Thursday': 'ˈθɜːrzdeɪ',
        'Friday': 'ˈfraɪdeɪ', 'Saturday': 'ˈsætərdeɪ', 'Sunday': 'ˈsʌndeɪ', 'Week': 'wiːk',
        'Spring': 'sprɪŋ', 'Summer': 'ˈsʌmər', 'Autumn': 'ˈɔːtəm', 'Winter': 'ˈwɪntər',
        'Circle': 'ˈsɜːrkl', 'Square': 'skwer', 'Triangle': 'ˈtraɪæŋɡl', 'Rectangle': 'ˈrektæŋɡl',
        'Beautiful': 'ˈbjuːtɪfl', 'Wonderful': 'ˈwʌndərfl', 'Excellent': 'ˈeksələnt', 'Perfect': 'ˈpɜːrfɪkt',
        'Amazing': 'əˈmeɪzɪŋ', 'Fantastic': 'fænˈtæstɪk', 'Brilliant': 'ˈbrɪljənt', 'Outstanding': 'aʊtˈstændɪŋ',
        'Mathematics': 'ˌmæθəˈmætɪks', 'Science': 'ˈsaɪəns', 'History': 'ˈhɪstri', 'Geography': 'dʒiˈɑːɡrəfi',
        'Physics': 'ˈfɪzɪks', 'Chemistry': 'ˈkemɪstri', 'Biology': 'baɪˈɑːlədʒi', 'English': 'ˈɪŋɡlɪʃ',
        'Happy': 'ˈhæpi', 'Sad': 'sæd', 'Angry': 'ˈæŋɡri', 'Excited': 'ɪkˈsaɪtɪd',
        'Worried': 'ˈwɜːrid', 'Surprised': 'sərˈpraɪzd', 'Disappointed': 'ˌdɪsəˈpɔɪntɪd', 'Proud': 'praʊd',
        'Morning': 'ˈmɔːrnɪŋ', 'Afternoon': 'ˌæftərˈnuːn', 'Evening': 'ˈiːvnɪŋ', 'Night': 'naɪt',
        'Today': 'təˈdeɪ', 'Tomorrow': 'təˈmɔːroʊ', 'Yesterday': 'ˈjestərdeɪ', 'Weekend': 'ˈwiːkend',
        'Environment': 'ɪnˈvaɪrənmənt', 'Pollution': 'pəˈluːʃn', 'Protect': 'prəˈtekt', 'Nature': 'ˈneɪtʃər',
        'Football': 'ˈfʊtbɔːl', 'Basketball': 'ˈbæskɪtbɔːl', 'Tennis': 'ˈtenɪs', 'Swimming': 'ˈswɪmɪŋ',
        'Volleyball': 'ˈvɑːlibɔːl', 'Baseball': 'ˈbeɪsbɔːl', 'Soccer': 'ˈsɑːkər', 'Badminton': 'ˈbædmɪntən',
        'Ship': 'ʃɪp', 'Bicycle': 'ˈbaɪsɪkl', 'Motorcycle': 'ˈmoʊtərsaɪkl', 'Subway': 'ˈsʌbweɪ',
        'Nurse': 'nɜːrs', 'Lawyer': 'ˈlɔːjər', 'Pilot': 'ˈpaɪlət', 'Chef': 'ʃef',
        'Wide': 'waɪd', 'Narrow': 'ˈnæroʊ', 'Thick': 'θɪk', 'Thin': 'θɪn',
        'Review': 'rɪˈvjuː', 'Memorize': 'ˈmeməraɪz', 'Understand': 'ˌʌndərˈstænd', 'Master': 'ˈmæstər',
        'Essential': 'ɪˈsenʃl', 'Significant': 'sɪɡˈnɪfɪkənt', 'Critical': 'ˈkrɪtɪkl', 'Crucial': 'ˈkruːʃl',
        'Challenge': 'ˈtʃælɪndʒ', 'Opportunity': 'ˌɑːpərˈtuːnəti', 'Success': 'səkˈses', 'Achievement': 'əˈtʃiːvmənt',
        'Difficult': 'ˈdɪfɪkəlt', 'Easy': 'ˈiːzi', 'Simple': 'ˈsɪmpl', 'Complex': 'kəmˈpleks',
        'Quickly': 'ˈkwɪkli', 'Slowly': 'ˈsloʊli', 'Carefully': 'ˈkerfəli', 'Suddenly': 'ˈsʌdənli',
        'In': 'ɪn', 'On': 'ɑːn', 'At': 'æt', 'By': 'baɪ',
        'And': 'ænd', 'But': 'bʌt', 'Or': 'ɔːr', 'So': 'soʊ',
        'Hello': 'həˈloʊ', 'Thanks': 'θæŋks', 'Sorry': 'ˈsɑːri', 'Please': 'pliːz',
        'Question': 'ˈkwestʃən', 'Answer': 'ˈænsər', 'Problem': 'ˈprɑːbləm', 'Solution': 'səˈluːʃn'
      };
      return phoneticMap[word] || '';
    },
    
    getExamples(word) {
      // 单词例句映射（每个单词两句例句）
      const examplesMap = {
        'Apple': [
          { en: 'I like to eat an apple.', cn: '我喜欢吃苹果。' },
          { en: 'The apple is red.', cn: '这个苹果是红色的。' }
        ],
        'Banana': [
          { en: 'Monkeys love bananas.', cn: '猴子喜欢香蕉。' },
          { en: 'I have a banana for breakfast.', cn: '我早餐吃一根香蕉。' }
        ],
        'Cat': [
          { en: 'The cat is sleeping.', cn: '猫在睡觉。' },
          { en: 'I have a pet cat.', cn: '我有一只宠物猫。' }
        ],
        'Dog': [
          { en: 'The dog is playing.', cn: '狗在玩耍。' },
          { en: 'My dog is very friendly.', cn: '我的狗很友好。' }
        ],
        'Bird': [
          { en: 'The bird is flying.', cn: '鸟在飞。' },
          { en: 'I can hear a bird singing.', cn: '我能听到鸟在唱歌。' }
        ],
        'Fish': [
          { en: 'The fish is swimming.', cn: '鱼在游泳。' },
          { en: 'I like to eat fish.', cn: '我喜欢吃鱼。' }
        ],
        'Book': [
          { en: 'I read a book every day.', cn: '我每天读一本书。' },
          { en: 'This is my favorite book.', cn: '这是我最喜欢的书。' }
        ],
        'Pen': [
          { en: 'I write with a pen.', cn: '我用笔写字。' },
          { en: 'Can I borrow your pen?', cn: '我能借你的笔吗？' }
        ],
        'Car': [
          { en: 'My father drives a car.', cn: '我爸爸开汽车。' },
          { en: 'The car is red.', cn: '这辆车是红色的。' }
        ],
        'Sun': [
          { en: 'The sun is shining.', cn: '太阳在照耀。' },
          { en: 'I like sunny days.', cn: '我喜欢晴天。' }
        ],
        'Red': [
          { en: 'The apple is red.', cn: '苹果是红色的。' },
          { en: 'I like red color.', cn: '我喜欢红色。' }
        ],
        'Run': [
          { en: 'I run every morning.', cn: '我每天早上跑步。' },
          { en: 'Let\'s run together.', cn: '我们一起跑步吧。' }
        ],
        'School': [
          { en: 'I go to school every day.', cn: '我每天去学校。' },
          { en: 'My school is very big.', cn: '我的学校很大。' }
        ],
        'Happy': [
          { en: 'I am very happy today.', cn: '我今天很开心。' },
          { en: 'She looks happy.', cn: '她看起来很开心。' }
        ],
        'Beautiful': [
          { en: 'The flower is beautiful.', cn: '这朵花很美丽。' },
          { en: 'You are beautiful.', cn: '你很美丽。' }
        ],
        'Orange': [
          { en: 'I like orange juice.', cn: '我喜欢橙汁。' },
          { en: 'The orange is sweet.', cn: '这个橙子很甜。' }
        ],
        'Grape': [
          { en: 'Grapes are my favorite fruit.', cn: '葡萄是我最喜欢的水果。' },
          { en: 'I eat grapes every day.', cn: '我每天吃葡萄。' }
        ],
        'Table': [
          { en: 'The table is big.', cn: '这张桌子很大。' },
          { en: 'I sit at the table.', cn: '我坐在桌子旁。' }
        ],
        'Chair': [
          { en: 'Please sit on the chair.', cn: '请坐在椅子上。' },
          { en: 'The chair is comfortable.', cn: '这把椅子很舒服。' }
        ],
        'Moon': [
          { en: 'The moon is bright tonight.', cn: '今晚月亮很亮。' },
          { en: 'I can see the moon.', cn: '我能看到月亮。' }
        ],
        'Star': [
          { en: 'Stars are in the sky.', cn: '星星在天空中。' },
          { en: 'I count the stars.', cn: '我数星星。' }
        ],
        'Blue': [
          { en: 'The sky is blue.', cn: '天空是蓝色的。' },
          { en: 'I like blue color.', cn: '我喜欢蓝色。' }
        ],
        'Green': [
          { en: 'The grass is green.', cn: '草是绿色的。' },
          { en: 'I wear a green shirt.', cn: '我穿一件绿色的衬衫。' }
        ],
        'Yellow': [
          { en: 'The sun is yellow.', cn: '太阳是黄色的。' },
          { en: 'I have a yellow pencil.', cn: '我有一支黄色的铅笔。' }
        ],
        'One': [
          { en: 'I have one apple.', cn: '我有一个苹果。' },
          { en: 'One plus one equals two.', cn: '一加一等于二。' }
        ],
        'Two': [
          { en: 'I have two hands.', cn: '我有两只手。' },
          { en: 'Two birds are flying.', cn: '两只鸟在飞。' }
        ],
        'Three': [
          { en: 'I have three books.', cn: '我有三本书。' },
          { en: 'Three is my lucky number.', cn: '三是我的幸运数字。' }
        ],
        'Four': [
          { en: 'There are four seasons.', cn: '有四个季节。' },
          { en: 'I count to four.', cn: '我数到四。' }
        ],
        'Teacher': [
          { en: 'My teacher is kind.', cn: '我的老师很和蔼。' },
          { en: 'I love my teacher.', cn: '我爱我的老师。' }
        ],
        'Student': [
          { en: 'I am a student.', cn: '我是一名学生。' },
          { en: 'Students study hard.', cn: '学生们努力学习。' }
        ],
        'Father': [
          { en: 'My father is tall.', cn: '我的父亲很高。' },
          { en: 'I love my father.', cn: '我爱我的父亲。' }
        ],
        'Mother': [
          { en: 'My mother is beautiful.', cn: '我的母亲很美丽。' },
          { en: 'I help my mother.', cn: '我帮助我的母亲。' }
        ],
        'Jump': [
          { en: 'I can jump high.', cn: '我能跳得很高。' },
          { en: 'Let\'s jump together.', cn: '我们一起跳吧。' }
        ],
        'Walk': [
          { en: 'I walk to school.', cn: '我步行去学校。' },
          { en: 'Let\'s take a walk.', cn: '我们去散步吧。' }
        ],
        'Sit': [
          { en: 'Please sit down.', cn: '请坐下。' },
          { en: 'I sit on the chair.', cn: '我坐在椅子上。' }
        ],
        'Lion': [
          { en: 'The lion is the king.', cn: '狮子是百兽之王。' },
          { en: 'I see a lion at the zoo.', cn: '我在动物园看到一只狮子。' }
        ],
        'Tiger': [
          { en: 'The tiger is strong.', cn: '老虎很强壮。' },
          { en: 'Tigers live in the forest.', cn: '老虎生活在森林里。' }
        ],
        'Elephant': [
          { en: 'The elephant is big.', cn: '大象很大。' },
          { en: 'Elephants have long trunks.', cn: '大象有长鼻子。' }
        ],
        'Monkey': [
          { en: 'The monkey likes bananas.', cn: '猴子喜欢香蕉。' },
          { en: 'Monkeys can climb trees.', cn: '猴子会爬树。' }
        ],
        'Wonderful': [
          { en: 'Today is a wonderful day.', cn: '今天是美好的一天。' },
          { en: 'You did a wonderful job.', cn: '你做得很好。' }
        ],
        'Excellent': [
          { en: 'Your work is excellent.', cn: '你的工作很优秀。' },
          { en: 'She is an excellent student.', cn: '她是一名优秀的学生。' }
        ],
        'Perfect': [
          { en: 'The weather is perfect.', cn: '天气很完美。' },
          { en: 'You are perfect.', cn: '你很完美。' }
        ],
        'Mathematics': [
          { en: 'I study mathematics at school.', cn: '我在学校学习数学。' },
          { en: 'Mathematics is interesting.', cn: '数学很有趣。' }
        ],
        'Science': [
          { en: 'I love science class.', cn: '我喜欢科学课。' },
          { en: 'Science is fun.', cn: '科学很有趣。' }
        ],
        'Sad': [
          { en: 'I feel sad today.', cn: '我今天感到悲伤。' },
          { en: 'Don\'t be sad.', cn: '不要难过。' }
        ],
        'Angry': [
          { en: 'My father is angry.', cn: '我的父亲生气了。' },
          { en: 'Don\'t be angry with me.', cn: '不要生我的气。' }
        ],
        'Excited': [
          { en: 'I am excited about the trip.', cn: '我对这次旅行很兴奋。' },
          { en: 'She looks excited.', cn: '她看起来很兴奋。' }
        ],
        'Morning': [
          { en: 'Good morning, teacher!', cn: '早上好，老师！' },
          { en: 'I get up early in the morning.', cn: '我早上起得很早。' }
        ],
        'Afternoon': [
          { en: 'I have lunch in the afternoon.', cn: '我下午吃午饭。' },
          { en: 'Good afternoon, everyone!', cn: '大家下午好！' }
        ],
        'Evening': [
          { en: 'I do homework in the evening.', cn: '我晚上做作业。' },
          { en: 'Good evening!', cn: '晚上好！' }
        ],
        'Night': [
          { en: 'I go to bed at night.', cn: '我晚上睡觉。' },
          { en: 'The night is quiet.', cn: '夜晚很安静。' }
        ],
        'Sunny': [
          { en: 'It\'s a sunny day today.', cn: '今天是晴天。' },
          { en: 'I like sunny weather.', cn: '我喜欢晴天。' }
        ],
        'Rainy': [
          { en: 'It\'s a rainy day.', cn: '今天是雨天。' },
          { en: 'I don\'t like rainy days.', cn: '我不喜欢雨天。' }
        ],
        'Cloudy': [
          { en: 'The sky is cloudy.', cn: '天空多云。' },
          { en: 'It\'s cloudy today.', cn: '今天多云。' }
        ],
        'Windy': [
          { en: 'It\'s windy outside.', cn: '外面有风。' },
          { en: 'The windy day is cool.', cn: '有风的日子很凉爽。' }
        ],
        'Football': [
          { en: 'I play football with friends.', cn: '我和朋友们踢足球。' },
          { en: 'Football is my favorite sport.', cn: '足球是我最喜欢的运动。' }
        ],
        'Basketball': [
          { en: 'I like to play basketball.', cn: '我喜欢打篮球。' },
          { en: 'Basketball is fun.', cn: '篮球很有趣。' }
        ],
        'Swimming': [
          { en: 'I go swimming in summer.', cn: '我夏天去游泳。' },
          { en: 'Swimming is good exercise.', cn: '游泳是很好的运动。' }
        ],
        'Bus': [
          { en: 'I take the bus to school.', cn: '我乘公交车去学校。' },
          { en: 'The bus is coming.', cn: '公交车来了。' }
        ],
        'Train': [
          { en: 'I travel by train.', cn: '我乘火车旅行。' },
          { en: 'The train is fast.', cn: '火车很快。' }
        ],
        'Doctor': [
          { en: 'The doctor helps sick people.', cn: '医生帮助生病的人。' },
          { en: 'I want to be a doctor.', cn: '我想成为一名医生。' }
        ],
        'Big': [
          { en: 'The elephant is big.', cn: '大象很大。' },
          { en: 'I have a big house.', cn: '我有一座大房子。' }
        ],
        'Small': [
          { en: 'The mouse is small.', cn: '老鼠很小。' },
          { en: 'I have a small bag.', cn: '我有一个小包。' }
        ],
        'Tall': [
          { en: 'My father is tall.', cn: '我的父亲很高。' },
          { en: 'The tree is tall.', cn: '这棵树很高。' }
        ],
        'Short': [
          { en: 'I am short.', cn: '我很矮。' },
          { en: 'The pencil is short.', cn: '这支铅笔很短。' }
        ],
        'Study': [
          { en: 'I study English every day.', cn: '我每天学习英语。' },
          { en: 'Let\'s study together.', cn: '我们一起学习吧。' }
        ],
        'Learn': [
          { en: 'I learn new words.', cn: '我学习新单词。' },
          { en: 'It\'s fun to learn.', cn: '学习很有趣。' }
        ],
        'Practice': [
          { en: 'I practice speaking English.', cn: '我练习说英语。' },
          { en: 'Practice makes perfect.', cn: '熟能生巧。' }
        ],
        'Important': [
          { en: 'Education is important.', cn: '教育很重要。' },
          { en: 'This is an important lesson.', cn: '这是重要的一课。' }
        ],
        'Challenge': [
          { en: 'This is a big challenge.', cn: '这是一个很大的挑战。' },
          { en: 'I like challenges.', cn: '我喜欢挑战。' }
        ],
        'Success': [
          { en: 'Hard work leads to success.', cn: '努力工作会带来成功。' },
          { en: 'I wish you success.', cn: '我祝你成功。' }
        ],
        'Hello': [
          { en: 'Hello, how are you?', cn: '你好，你好吗？' },
          { en: 'I say hello to my friend.', cn: '我向我的朋友问好。' }
        ],
        'Thanks': [
          { en: 'Thanks for your help.', cn: '谢谢你的帮助。' },
          { en: 'I say thanks to my teacher.', cn: '我向我的老师道谢。' }
        ],
        'Sorry': [
          { en: 'I am sorry for being late.', cn: '对不起，我迟到了。' },
          { en: 'Sorry, I made a mistake.', cn: '对不起，我犯了一个错误。' }
        ],
        'Please': [
          { en: 'Please help me.', cn: '请帮助我。' },
          { en: 'Please sit down.', cn: '请坐下。' }
        ]
      };
      
      // 如果没有找到例句，生成通用例句
      if (!examplesMap[word]) {
        const chinese = this.getChineseTranslation(word);
        return [
          { en: `This is a ${word.toLowerCase()}.`, cn: `这是一个${chinese}。` },
          { en: `I like ${word.toLowerCase()}.`, cn: `我喜欢${chinese}。` }
        ];
      }
      
      return examplesMap[word];
    },
    
    generateLetterOptions(letter) {
      // 字母选项：直接显示字母，不使用图片
      const allLetters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
      const wrongLetters = allLetters.filter(l => l !== letter).sort(() => Math.random() - 0.5).slice(0, 3);
      const options = [
        { text: letter, image: null, isCorrect: true },
        ...wrongLetters.map(l => ({ text: l, image: null, isCorrect: false }))
      ];
      return options.sort(() => Math.random() - 0.5);
    },
    
    generateWordOptions(word, chinese, wrongWords) {
      // 单词选项：显示真实图片
      const options = [
        { 
          text: chinese, 
          image: this.getWordImage(word), 
          isCorrect: true 
        },
        ...wrongWords.map(w => ({ 
          text: this.getChineseTranslation(w), 
          image: this.getWordImage(w), 
          isCorrect: false 
        }))
      ];
      return options.sort(() => Math.random() - 0.5);
    },
    
    getWordImage(word) {
      // 优先使用emoji，如果找不到则使用图片API
      // 使用Pixabay API（免费，适合儿童图片）或使用emoji
      const emoji = this.getWordEmoji(word);
      if (emoji) {
        // 如果有emoji，直接返回null，让前端显示emoji
        return null;
      }
      
      // 如果没有emoji，尝试使用图片API
      // 使用Picsum Photos作为备用（虽然不一定是儿童友好，但至少能显示）
      const seed = word.toLowerCase().replace(/\s+/g, '-');
      return `https://picsum.photos/seed/${seed}-child/300/300`;
    },
    
    handleImageError(event) {
      // 如果图片加载失败，使用emoji作为备用
      const word = event.target.alt || '';
      const emoji = this.getWordEmoji(word);
      if (emoji) {
        // 创建一个包含emoji的div来替换图片
        const parent = event.target.parentElement;
        if (parent) {
          parent.innerHTML = `<div class="emoji-fallback">${emoji}</div>`;
        }
      } else {
        // 如果找不到emoji，使用默认图片
        event.target.src = 'https://via.placeholder.com/300/667eea/FFFFFF?text=' + encodeURIComponent(word);
      }
    },
    
    getWordEmojiFromText(chineseText) {
      // 从中文文本反向查找对应的英文单词，然后返回emoji
      const reverseMap = {
        '苹果': '🍎', '香蕉': '🍌', '橙子': '🍊', '葡萄': '🍇',
        '书': '📚', '笔': '✏️', '桌子': '🪑', '椅子': '💺',
        '猫': '🐱', '狗': '🐶', '鸟': '🐦', '鱼': '🐟',
        '汽车': '🚗', '公交车': '🚌', '自行车': '🚲', '火车': '🚂',
        '头': '👤', '手': '✋', '脚': '🦶', '眼睛': '👁️',
        '红色': '🔴', '蓝色': '🔵', '绿色': '🟢', '黄色': '🟡',
        '一': '1️⃣', '二': '2️⃣', '三': '3️⃣', '四': '4️⃣',
        '面包': '🍞', '牛奶': '🥛', '鸡蛋': '🥚', '米饭': '🍚',
        '学校': '🏫', '老师': '👩‍🏫', '学生': '👨‍🎓', '班级': '📖',
        '父亲': '👨', '母亲': '👩', '兄弟': '👦', '姐妹': '👧',
        '太阳': '☀️', '月亮': '🌙', '星星': '⭐', '云': '☁️',
        '晴朗的': '☀️', '下雨的': '🌧️', '多云的': '☁️', '有风的': '💨',
        '跑': '🏃', '跳': '🤸', '走': '🚶', '坐': '🪑',
        '狮子': '🦁', '老虎': '🐯', '大象': '🐘', '猴子': '🐵',
        '粉色': '🌸', '紫色': '🟣', '棕色': '🤎',
        '五': '5️⃣', '六': '6️⃣', '七': '7️⃣', '八': '8️⃣',
        '鼻子': '👃', '嘴巴': '👄', '耳朵': '👂', '腿': '🦵',
        '爷爷': '👴', '奶奶': '👵', '叔叔': '👨', '阿姨': '👩',
        '黑板': '📋',
        '站': '🧍', '睡觉': '😴', '吃': '🍽️', '喝': '🥤',
        '星期一': '📅', '星期二': '📅', '星期三': '📅', '星期四': '📅',
        '星期五': '📅', '星期六': '📅', '星期日': '📅', '星期': '📆',
        '春天': '🌸', '夏天': '☀️', '秋天': '🍂', '冬天': '❄️',
        '圆形': '⭕', '正方形': '⬜', '三角形': '🔺', '长方形': '▭'
      };
      return reverseMap[chineseText] || '📷';
    },
    
    getWordEmoji(word) {
      // 单词到emoji的映射（适合儿童）
      const wordEmojiMap = {
        'Apple': '🍎', 'Banana': '🍌', 'Orange': '🍊', 'Grape': '🍇',
        'Book': '📚', 'Pen': '✏️', 'Table': '🪑', 'Chair': '💺',
        'Cat': '🐱', 'Dog': '🐶', 'Bird': '🐦', 'Fish': '🐟',
        'Car': '🚗', 'Bus': '🚌', 'Bike': '🚲', 'Train': '🚂',
        'Head': '👤', 'Hand': '✋', 'Foot': '🦶', 'Eye': '👁️',
        'Red': '🔴', 'Blue': '🔵', 'Green': '🟢', 'Yellow': '🟡',
        'One': '1️⃣', 'Two': '2️⃣', 'Three': '3️⃣', 'Four': '4️⃣',
        'Bread': '🍞', 'Milk': '🥛', 'Egg': '🥚', 'Rice': '🍚',
        'School': '🏫', 'Teacher': '👩‍🏫', 'Student': '👨‍🎓', 'Class': '📖',
        'Father': '👨', 'Mother': '👩', 'Brother': '👦', 'Sister': '👧',
        'Sun': '☀️', 'Moon': '🌙', 'Star': '⭐', 'Cloud': '☁️',
        'Sunny': '☀️', 'Rainy': '🌧️', 'Cloudy': '☁️', 'Windy': '💨',
        'Run': '🏃', 'Jump': '🤸', 'Walk': '🚶', 'Sit': '🪑',
        'Lion': '🦁', 'Tiger': '🐯', 'Elephant': '🐘', 'Monkey': '🐵',
        'Pink': '🌸', 'Purple': '🟣', 'Brown': '🤎',
        'Five': '5️⃣', 'Six': '6️⃣', 'Seven': '7️⃣', 'Eight': '8️⃣',
        'Nose': '👃', 'Mouth': '👄', 'Ear': '👂', 'Leg': '🦵',
        'Grandpa': '👴', 'Grandma': '👵', 'Uncle': '👨', 'Aunt': '👩',
        'Desk': '🪑', 'Blackboard': '📋',
        'Stand': '🧍', 'Sleep': '😴', 'Eat': '🍽️', 'Drink': '🥤',
        'Monday': '📅', 'Tuesday': '📅', 'Wednesday': '📅', 'Thursday': '📅',
        'Friday': '📅', 'Saturday': '📅', 'Sunday': '📅', 'Week': '📆',
        'Spring': '🌸', 'Summer': '☀️', 'Autumn': '🍂', 'Winter': '❄️',
        'Circle': '⭕', 'Square': '⬜', 'Triangle': '🔺', 'Rectangle': '▭'
      };
      return wordEmojiMap[word] || null;
    },
    
    getRandomWords(wordList, excludeWord) {
      const available = wordList.filter(w => w !== excludeWord);
      return available.sort(() => Math.random() - 0.5).slice(0, 3);
    },
    
    getChineseTranslation(word) {
      // 简单的翻译映射，实际应该从API获取
      const translations = {
        'Apple': '苹果', 'Banana': '香蕉', 'Orange': '橙子', 'Grape': '葡萄',
        'Book': '书', 'Pen': '笔', 'Table': '桌子', 'Chair': '椅子',
        'Cat': '猫', 'Dog': '狗', 'Bird': '鸟', 'Fish': '鱼',
        'Sun': '太阳', 'Moon': '月亮', 'Star': '星星', 'Cloud': '云',
        'Lion': '狮子', 'Tiger': '老虎', 'Elephant': '大象', 'Monkey': '猴子',
        'Red': '红色', 'Blue': '蓝色', 'Green': '绿色', 'Yellow': '黄色',
        'One': '一', 'Two': '二', 'Three': '三', 'Four': '四',
        'Head': '头', 'Hand': '手', 'Foot': '脚', 'Eye': '眼睛',
        'Father': '父亲', 'Mother': '母亲', 'Brother': '兄弟', 'Sister': '姐妹',
        'School': '学校', 'Teacher': '老师', 'Student': '学生', 'Class': '班级',
        'Bread': '面包', 'Milk': '牛奶', 'Egg': '鸡蛋', 'Rice': '米饭',
        'Run': '跑', 'Jump': '跳', 'Walk': '走', 'Sit': '坐', 'Stand': '站', 'Sleep': '睡觉', 'Eat': '吃', 'Drink': '喝',
        'Bike': '自行车', 'Train': '火车',
        'Nose': '鼻子', 'Mouth': '嘴巴', 'Ear': '耳朵', 'Leg': '腿',
        'Grandpa': '爷爷', 'Grandma': '奶奶', 'Uncle': '叔叔', 'Aunt': '阿姨',
        'Desk': '桌子', 'Blackboard': '黑板',
        'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三', 'Thursday': '星期四',
        'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日', 'Week': '星期',
        'Spring': '春天', 'Summer': '夏天', 'Autumn': '秋天', 'Winter': '冬天',
        'Circle': '圆形', 'Square': '正方形', 'Triangle': '三角形', 'Rectangle': '长方形',
        'Beautiful': '美丽的', 'Wonderful': '精彩的', 'Excellent': '优秀的', 'Perfect': '完美的',
        'Amazing': '令人惊奇的', 'Fantastic': '极好的', 'Brilliant': '杰出的', 'Outstanding': '出色的',
        'Mathematics': '数学', 'Science': '科学', 'History': '历史', 'Geography': '地理',
        'Physics': '物理', 'Chemistry': '化学', 'Biology': '生物', 'English': '英语',
        'Happy': '快乐的', 'Sad': '悲伤的', 'Angry': '生气的', 'Excited': '兴奋的',
        'Worried': '担心的', 'Surprised': '惊讶的', 'Disappointed': '失望的', 'Proud': '骄傲的',
        'Morning': '早晨', 'Afternoon': '下午', 'Evening': '晚上', 'Night': '夜晚',
        'Today': '今天', 'Tomorrow': '明天', 'Yesterday': '昨天', 'Weekend': '周末',
        'Sunny': '晴朗的', 'Rainy': '下雨的', 'Cloudy': '多云的', 'Windy': '有风的',
        'Environment': '环境', 'Pollution': '污染', 'Protect': '保护', 'Nature': '自然',
        'Football': '足球', 'Basketball': '篮球', 'Tennis': '网球', 'Swimming': '游泳',
        'Volleyball': '排球', 'Baseball': '棒球', 'Soccer': '足球', 'Badminton': '羽毛球',
        'Car': '汽车', 'Bus': '公交车', 'Train': '火车', 'Airplane': '飞机',
        'Ship': '船', 'Bicycle': '自行车', 'Motorcycle': '摩托车', 'Subway': '地铁',
        'Doctor': '医生', 'Teacher': '老师', 'Engineer': '工程师', 'Artist': '艺术家',
        'Nurse': '护士', 'Lawyer': '律师', 'Pilot': '飞行员', 'Chef': '厨师',
        'Big': '大的', 'Small': '小的', 'Tall': '高的', 'Short': '矮的',
        'Wide': '宽的', 'Narrow': '窄的', 'Thick': '厚的', 'Thin': '薄的',
        'Study': '学习', 'Learn': '学会', 'Practice': '练习', 'Improve': '提高',
        'Review': '复习', 'Memorize': '记忆', 'Understand': '理解', 'Master': '掌握',
        'Important': '重要的', 'Necessary': '必要的', 'Useful': '有用的', 'Valuable': '有价值的',
        'Essential': '必要的', 'Significant': '重要的', 'Critical': '关键的', 'Crucial': '至关重要的',
        'Challenge': '挑战', 'Opportunity': '机会', 'Success': '成功', 'Achievement': '成就',
        'Difficult': '困难的', 'Easy': '容易的', 'Simple': '简单的', 'Complex': '复杂的',
        'Quickly': '快速地', 'Slowly': '慢慢地', 'Carefully': '仔细地', 'Suddenly': '突然地',
        'In': '在...里', 'On': '在...上', 'At': '在', 'By': '通过',
        'And': '和', 'But': '但是', 'Or': '或者', 'So': '所以',
        'Hello': '你好', 'Thanks': '谢谢', 'Sorry': '对不起', 'Please': '请',
        'Question': '问题', 'Answer': '答案', 'Problem': '问题', 'Solution': '解决方案'
      };
      return translations[word] || word;
    },
    
    selectAnswer(index) {
      if (this.showAnswer) return;
      
      this.selectedAnswer = index;
      const isCorrect = this.currentQuestion.options[index].isCorrect;
      this.showAnswer = true;
      
      if (isCorrect) {
        this.correctCount++;
        this.feedbackType = 'correct';
        this.feedbackMessage = '太棒了！答对了！';
        // 播放正确音效（可以后续添加）
      } else {
        this.feedbackType = 'wrong';
        this.feedbackMessage = '再想想吧！';
        // 记录错误单词
        if (!this.isLetterQuestion && this.currentQuestion.word) {
          const wrongWord = {
            word: this.currentQuestion.word,
            chinese: this.currentQuestion.chinese,
            phonetic: this.currentQuestion.phonetic
          };
          // 避免重复添加
          if (!this.wrongWords.find(w => w.word === wrongWord.word)) {
            this.wrongWords.push(wrongWord);
          }
        }
        // 播放错误音效（可以后续添加）
      }
      
      this.showFeedback = true;
      this.showNextButton = true;
    },
    
    playWordSound(word = null) {
      // 防抖处理：如果正在播放，取消之前的播放
      if (this.playSoundTimeout) {
        clearTimeout(this.playSoundTimeout);
        this.playSoundTimeout = null;
      }
      
      // 如果正在播放，立即停止
      if (this.isPlayingSound) {
        window.speechSynthesis.cancel();
        this.isPlayingSound = false;
      }
      
      // 获取要播放的单词
      let wordToSpeak = null;
      
      if (word) {
        wordToSpeak = word;
      } else if (this.currentQuestion && this.currentQuestion.word) {
        wordToSpeak = this.currentQuestion.word;
      }
      
      if (!wordToSpeak) {
        return;
      }
      
      // 确保wordToSpeak是字符串
      wordToSpeak = String(wordToSpeak).trim();
      
      // 如果是对象，尝试获取word属性
      if (typeof wordToSpeak === 'object' && wordToSpeak.word) {
        wordToSpeak = wordToSpeak.word;
        wordToSpeak = String(wordToSpeak).trim();
      }
      
      // 验证是否是英文单词（只包含英文字母，可能包含连字符或空格）
      const englishWordPattern = /^[A-Za-z\s\-']+$/;
      if (!englishWordPattern.test(wordToSpeak)) {
        // 如果包含中文字符，尝试提取英文部分
        const englishMatch = wordToSpeak.match(/[A-Za-z\s\-']+/);
        if (englishMatch) {
          wordToSpeak = englishMatch[0].trim();
        } else {
          return;
        }
      }
      
      // 使用防抖，避免快速点击导致的问题
      this.playSoundTimeout = setTimeout(() => {
        this.playSoundTimeout = null;
        this._doPlaySound(wordToSpeak);
      }, 50); // 减少延迟时间
    },
    
    _doPlaySound(wordToSpeak) {
      try {
        // 确保之前的播放已停止
        if (window.speechSynthesis.speaking) {
          window.speechSynthesis.cancel();
        }
        
        // 创建语音对象
        const utterance = new SpeechSynthesisUtterance(wordToSpeak);
        
        // 设置语音参数
        utterance.lang = 'en-US';
        utterance.text = wordToSpeak;
        utterance.rate = 0.9; // 稍微提高语速，减少卡顿感
        utterance.pitch = 1.0;
        utterance.volume = 1.0;
        
        // 事件处理
        utterance.onstart = () => {
          this.isPlayingSound = true;
        };
        
        utterance.onend = () => {
          this.isPlayingSound = false;
        };
        
        utterance.onerror = () => {
          this.isPlayingSound = false;
        };
        
        // 立即播放，不使用延迟
        window.speechSynthesis.speak(utterance);
      } catch (error) {
        this.isPlayingSound = false;
        console.error('播放发音时发生错误:', error);
      }
    },
    
    nextQuestion() {
      if (this.currentQuestionIndex < this.questions.length - 1) {
        this.currentQuestionIndex++;
        this.selectedAnswer = null;
        this.showAnswer = false;
        this.showFeedback = false;
        this.showNextButton = false;
      } else {
        this.showLevelReward();
      }
    },
    
    showLevelReward() {
      const accuracy = Math.round((this.correctCount / this.questions.length) * 100);
      
      // 更新关卡状态
      const levelIndex = this.gameLevels.findIndex(l => l.id === this.currentLevel.id);
      
      if (levelIndex === -1) return;
      
      // 获取历史记录
      const progressKey = `game_progress_${this.currentDifficulty}`;
      const progress = JSON.parse(localStorage.getItem(progressKey) || '{}');
      const levelKey = `level_${this.currentLevel.level}`;
      const previousRecord = progress[levelKey] || {};
      
      // 判断是否通过：只有100%才算通过
      const passed = accuracy === 100;
      
      // 判断是否是第一次闯关
      const isFirstAttempt = !previousRecord.completeTime;
      
      // 获取历史最高准确率
      const bestAccuracy = Math.max(accuracy, previousRecord.bestAccuracy || 0);
      
      // 判断是否是第一次达到75%和100%
      const firstTime75 = isFirstAttempt && accuracy >= 75 && accuracy < 100;
      const firstTime100 = (isFirstAttempt && accuracy === 100) || 
                          (!isFirstAttempt && previousRecord.bestAccuracy < 100 && accuracy === 100);
      
      // 判断是否是一次性通过（第一次就100%）
      const oneTimePass = isFirstAttempt && accuracy === 100;
      
      // 计算本次获得的星星积分
      let earnedStarsThisTime = 0;
      
      if (oneTimePass) {
        // 一次性通过：获得3个星星积分
        earnedStarsThisTime = 3;
      } else if (firstTime75) {
        // 第一次达到75%：获得1个星星积分
        earnedStarsThisTime = 1;
      } else if (firstTime100) {
        // 第一次达到100%（之前有过75%）：获得1个星星积分
        earnedStarsThisTime = 1;
      } else {
        // 重复闯关：不获得星星积分
        earnedStarsThisTime = 0;
      }
      
      // 计算总星星数（历史累计）
      // 如果旧记录没有totalStars，先迁移
      let previousTotalStars = previousRecord.totalStars;
      if (previousTotalStars === undefined && previousRecord.completeTime) {
        // 旧数据迁移
        previousTotalStars = this.migrateOldStars(previousRecord);
        // 更新旧记录
        if (previousTotalStars > 0) {
          previousRecord.totalStars = previousTotalStars;
          progress[levelKey] = previousRecord;
          localStorage.setItem(progressKey, JSON.stringify(progress));
        }
      }
      const totalStars = (previousTotalStars || 0) + earnedStarsThisTime;
      
      // 计算显示星星数（用于地图显示）
      let displayStars = 0;
      if (bestAccuracy === 100) {
        displayStars = 3; // 100%显示3颗星
      } else if (bestAccuracy >= 75) {
        displayStars = 2; // 75%显示2颗星
      } else if (bestAccuracy > 0) {
        displayStars = 1; // 其他显示1颗星
      }
      
      // 更新关卡状态
      // 只要闯过（有记录）就显示在地图上，不管是否通过
      const hasAttempted = bestAccuracy > 0;
      
      if (hasAttempted) {
        this.gameLevels[levelIndex].attempted = true;
        this.gameLevels[levelIndex].stars = displayStars;
        this.gameLevels[levelIndex].bestAccuracy = bestAccuracy;
        
        // 只有100%才能解锁下一关
        if (passed) {
          this.gameLevels[levelIndex].completed = true;
          // 解锁下一关
          if (levelIndex < this.gameLevels.length - 1) {
            this.gameLevels[levelIndex + 1].unlocked = true;
          }
        } else {
          // 未通过，保持未完成状态
          this.gameLevels[levelIndex].completed = false;
        }
      }
      
      // 保存进度到localStorage
      progress[levelKey] = {
        completed: passed,
        passed: passed,
        attempted: hasAttempted,
        stars: displayStars, // 显示星星数
        totalStars: totalStars, // 累计星星积分
        earnedStarsThisTime: earnedStarsThisTime, // 本次获得的星星
        accuracy: accuracy, // 本次准确率
        bestAccuracy: bestAccuracy, // 历史最高准确率
        completeTime: new Date().toISOString(),
        wrongWords: this.wrongWords,
        levelName: this.currentLevel.name,
        difficulty: this.currentDifficulty,
        isFirstAttempt: isFirstAttempt,
        oneTimePass: oneTimePass
      };
      
      // 重新计算当前难度的完成数（只计算100%通过的）
      const currentDifficultyCompleted = this.gameLevels.filter(l => l.completed).length;
      progress.completedCount = currentDifficultyCompleted;
      localStorage.setItem(progressKey, JSON.stringify(progress));
      
      // 更新显示的星星数
      this.earnedStars = displayStars;
      // 保存本次获得的星星积分
      this.earnedStarsThisTime = earnedStarsThisTime;
      
      // 更新所有难度的总进度
      this.updateAllProgress();
      
      // 检查成就
      this.checkAchievements();
      
      this.currentView = 'reward';
    },
    
    checkAchievements() {
      // 检查成就解锁条件
      if (this.completedLevels >= 1 && !this.achievements[0].unlocked) {
        this.achievements[0].unlocked = true;
        this.achievements[0].unlockDate = new Date().toLocaleDateString('zh-CN');
      }
      
      const accuracy = (this.correctCount / this.questions.length) * 100;
      if (accuracy === 100 && !this.achievements[2].unlocked) {
        this.achievements[2].unlocked = true;
        this.achievements[2].unlockDate = new Date().toLocaleDateString('zh-CN');
      }
      
      if (this.completedLevels === this.totalLevels && !this.achievements[3].unlocked) {
        this.achievements[3].unlocked = true;
        this.achievements[3].unlockDate = new Date().toLocaleDateString('zh-CN');
      }
    },
    
    backToMap() {
      this.currentView = 'map';
      this.currentLevel = null;
    },
    
    nextLevel() {
      const nextLevel = this.gameLevels.find(l => l.level === this.currentLevel.level + 1);
      if (nextLevel && nextLevel.unlocked) {
        this.selectLevel(nextLevel);
      } else {
        this.backToMap();
      }
    },
    
    showProgressView() {
      this.currentView = 'progress';
    },
    
    showLeaderboard() {
      this.currentView = 'leaderboard';
      this.loadLeaderboard();
    },
    
    async loadLeaderboard() {
      this.loadingLeaderboard = true;
      try {
        // 获取当前学生信息
        let user = userService.getCurrentUser();
        this.currentStudent = user;
        
        // 获取当前学生的班级信息
        let classId = null;
        
        // 如果是本班级排名，必须获取classId
        if (this.leaderboardTab === 'class') {
          if (user) {
            // 尝试从不同字段获取classId
            classId = user.classId || 
                     user.class_id || 
                     user.assignedClassId || 
                     (user.childInfo && user.childInfo.assignedClassId) ||
                     null;
            
            // 如果前端没有classId，从后端获取用户信息
            if (!classId) {
              try {
                const userInfoResponse = await childEnglishApi.getUserInfo();
                if (userInfoResponse && userInfoResponse.code === 200 && userInfoResponse.data) {
                  const updatedUser = userInfoResponse.data.user;
                  classId = updatedUser.classId || updatedUser.class_id || null;
                  // 更新本地用户数据
                  if (classId) {
                    user.classId = classId;
                    user.className = updatedUser.className || user.className;
                    userService.setUser(user);
                    this.currentStudent = user;
                  }
                }
              } catch (error) {
                console.warn('获取用户信息失败:', error);
              }
            }
          }
          
          // 如果仍然没有classId，提示用户
          if (!classId) {
            console.warn('无法获取班级ID，将显示全部排名');
            // 如果无法获取班级ID，切换到全部排名
            this.leaderboardTab = 'all';
          }
        }
        
        // 如果是本班级排名，传递classId；如果是全部排名，传递null
        const requestClassId = this.leaderboardTab === 'class' ? classId : null;
        
        // 从后端获取排行榜数据
        try {
          const response = await childEnglishApi.getLeaderboard(requestClassId);
          if (response && response.code === 200 && response.data) {
            // 处理后端返回的数据
            let ranking = response.data.ranking || [];
            
            // 从localStorage获取所有学生的星星积分
            const starsMap = this.getAllStudentsStars();
            
            // 合并星星积分到学生数据
            ranking = ranking.map(student => {
              const studentId = student.id;
              const stars = starsMap.get(studentId) || 0;
              return {
                ...student,
                totalStars: stars
              };
            });
            
            // 按星星积分排序（积分高的在前）
            ranking.sort((a, b) => (b.totalStars || 0) - (a.totalStars || 0));
            
            if (this.leaderboardTab === 'class') {
              this.classRanking = ranking;
            } else {
              this.allRanking = ranking;
            }
          } else {
            // 如果后端没有数据，使用本地数据（模拟）
            this.loadLocalLeaderboard();
          }
        } catch (error) {
          console.warn('获取排行榜失败，使用本地数据:', error);
          // 使用本地数据（模拟）
          this.loadLocalLeaderboard();
        }
      } catch (error) {
        console.error('加载排行榜失败:', error);
        this.loadLocalLeaderboard();
      } finally {
        this.loadingLeaderboard = false;
      }
    },
    
    getAllStudentsStars() {
      // 从localStorage获取所有学生的星星积分
      // 格式：game_progress_easy, game_progress_medium, game_progress_hard
      const starsMap = new Map();
      const difficulties = ['easy', 'medium', 'hard'];
      
      // 遍历所有难度
      difficulties.forEach(difficulty => {
        const progressKey = `game_progress_${difficulty}`;
        const progress = JSON.parse(localStorage.getItem(progressKey) || '{}');
        
        // 遍历所有关卡记录
        Object.keys(progress).forEach(levelKey => {
          if (levelKey.startsWith('level_')) {
            const levelData = progress[levelKey];
            // 这里需要知道是哪个学生的数据
            // 由于localStorage是本地存储，我们假设当前用户的数据
            // 实际应该从后端获取每个学生的积分
          }
        });
      });
      
      // 获取当前用户的星星积分
      const user = userService.getCurrentUser();
      if (user && user.id) {
        const totalStars = this.totalStars;
        starsMap.set(user.id, totalStars);
      }
      
      return starsMap;
    },
    
    loadLocalLeaderboard() {
      // 从localStorage获取所有学生的星星积分（模拟数据）
      // 实际应该从后端获取
      const user = userService.getCurrentUser();
      const classId = user?.classId || null;
      const className = user?.className || '未知班级';
      const currentStars = this.totalStars;
      
      // 模拟数据：从localStorage读取所有学生的游戏进度
      // 这里只是示例，实际应该从后端获取
      const mockRanking = [
        {
          id: user?.id || 'current',
          name: user?.name || user?.username || '我',
          className: className,
          totalStars: currentStars
        }
      ];
      
      // 添加一些模拟数据用于演示
      if (this.leaderboardTab === 'class') {
        // 本班级排名：只显示当前班级的学生
        this.classRanking = mockRanking.sort((a, b) => (b.totalStars || 0) - (a.totalStars || 0));
      } else {
        // 全部排名：显示所有学生
        const allMockRanking = [
          ...mockRanking,
          { id: '1', name: '小明', className: '一年级1班', totalStars: 25 },
          { id: '2', name: '小红', className: '一年级2班', totalStars: 20 },
          { id: '3', name: '小刚', className: '一年级1班', totalStars: 18 },
          { id: '4', name: '小丽', className: '一年级3班', totalStars: 15 },
          { id: '5', name: '小强', className: '一年级2班', totalStars: 12 }
        ];
        this.allRanking = allMockRanking.sort((a, b) => (b.totalStars || 0) - (a.totalStars || 0));
      }
    },
    
    getLevelName(difficulty, level) {
      // 根据难度和关卡号获取关卡名称
      const levelConfigs = this.getLevelConfigsByDifficultyStatic(difficulty);
      if (levelConfigs && levelConfigs[level - 1]) {
        return levelConfigs[level - 1].name;
      }
      return `第${level}关`;
    },
    
    getLevelConfigsByDifficultyStatic(difficulty) {
      // 静态方法获取关卡配置（不依赖this.currentDifficulty）
      if (difficulty === 'easy') {
        const levels = [];
        const letterGroups = [
          { name: '字母A-D' },
          { name: '字母E-H' },
          { name: '字母I-L' },
          { name: '字母M-P' },
          { name: '字母Q-T' },
          { name: '字母U-X' }
        ];
        letterGroups.forEach(group => levels.push(group));
        const commonObjects = [
          { name: '水果乐园' },
          { name: '日常用品' },
          { name: '动物朋友' },
          { name: '交通工具' },
          { name: '身体部位' },
          { name: '颜色世界' },
          { name: '数字王国' },
          { name: '食物天地' },
          { name: '学校用品' },
          { name: '家庭成员' },
          { name: '自然景观' },
          { name: '天气变化' },
          { name: '动作词汇' },
          { name: '综合练习' }
        ];
        commonObjects.forEach(obj => levels.push(obj));
        return levels;
      } else if (difficulty === 'medium') {
        return [
          { name: '基础单词1' }, { name: '基础单词2' }, { name: '基础单词3' },
          { name: '动物世界' }, { name: '动物朋友' }, { name: '颜色认知' },
          { name: '多彩世界' }, { name: '数字学习' }, { name: '数字应用' },
          { name: '身体部位' }, { name: '身体认知' }, { name: '家庭成员' },
          { name: '家庭关系' }, { name: '学校用品' }, { name: '校园生活' },
          { name: '食物单词' }, { name: '美味食物' }, { name: '动作单词' },
          { name: '日常动作' }, { name: '时间表达' }, { name: '星期月份' },
          { name: '天气词汇' }, { name: '季节变化' }, { name: '形状认知' },
          { name: '综合测试' }
        ];
      } else {
        return [
          { name: '初中基础1' }, { name: '初中基础2' }, { name: '初中基础3' },
          { name: '学科词汇' }, { name: '数学词汇' }, { name: '科学词汇' },
          { name: '情感表达' }, { name: '情绪词汇' }, { name: '时间表达' },
          { name: '时间管理' }, { name: '天气词汇' }, { name: '气候环境' },
          { name: '运动项目' }, { name: '体育运动' }, { name: '交通工具' },
          { name: '出行方式' }, { name: '职业词汇' }, { name: '工作职业' },
          { name: '形容词1' }, { name: '形容词2' }, { name: '动词短语1' },
          { name: '动词短语2' }, { name: '名词词汇' }, { name: '副词应用' },
          { name: '介词用法' }, { name: '连词连接' }, { name: '日常对话' },
          { name: '情景交际' }, { name: '阅读理解' }, { name: '综合测试' }
        ];
      }
    },
    
    formatDateTime(dateString) {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    viewWrongWords(record) {
      this.currentWrongWordsRecord = record;
      this.showWrongWordsModal = true;
    },
    
    goBack() {
      if (this.currentView === 'difficulty') {
        this.$router.push('/');
      } else if (this.currentView === 'map') {
        this.backToDifficulty();
      } else if (this.currentView === 'progress') {
        this.currentView = this.currentDifficulty ? 'map' : 'difficulty';
      } else if (this.currentView === 'leaderboard') {
        this.currentView = this.currentDifficulty ? 'map' : 'difficulty';
      } else {
        this.currentView = 'map';
      }
    }
  }
};
</script>

<style scoped>
.game-learning {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
}

/* 页面头部 */
.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  flex-wrap: wrap;
}

.back-btn {
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateX(-5px);
}

.page-header h1 {
  margin: 0;
  color: white;
  font-size: 28px;
  font-weight: 600;
  flex: 1;
}

.header-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  padding: 8px 15px;
  border-radius: 20px;
  color: white;
  font-weight: 600;
}

.stat-item.clickable {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-item.clickable:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.stat-icon {
  font-size: 18px;
}

/* 难度选择界面 */
.difficulty-selection-container {
  max-width: 1200px;
  margin: 0 auto;
}

.difficulty-title {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.difficulty-title h2 {
  font-size: 32px;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.difficulty-title p {
  font-size: 18px;
  opacity: 0.9;
}

.difficulty-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  margin-top: 40px;
}

.difficulty-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border: 3px solid transparent;
}

.difficulty-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.difficulty-card.easy {
  border-color: #4CAF50;
}

.difficulty-card.easy:hover {
  background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
}

.difficulty-card.medium {
  border-color: #FF9800;
}

.difficulty-card.medium:hover {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
}

.difficulty-card.hard {
  border-color: #F44336;
}

.difficulty-card.hard:hover {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
}

.difficulty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.difficulty-name {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 15px;
}

.difficulty-desc {
  font-size: 16px;
  color: #7f8c8d;
  margin-bottom: 25px;
  line-height: 1.6;
}

.difficulty-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #ecf0f1;
}

.difficulty-stats .stat {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.difficulty-stats .stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.difficulty-stats .stat-value {
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
}

/* 游戏地图界面 */
.game-map-container {
  max-width: 1400px;
  margin: 0 auto;
}

.back-to-difficulty-btn {
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  margin-bottom: 20px;
}

.back-to-difficulty-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateX(-5px);
}

.map-title {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.map-title h2 {
  font-size: 32px;
  margin-bottom: 10px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.map-title p {
  font-size: 18px;
  opacity: 0.9;
}

.map-wrapper {
  position: relative;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px 20px 80px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  min-height: 500px;
  overflow: hidden;
}

.map-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    linear-gradient(180deg, #87CEEB 0%, #98D8C8 30%, #F0E68C 60%, #DDA0DD 100%),
    radial-gradient(circle at 20% 30%, rgba(135, 206, 235, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 70%, rgba(221, 160, 221, 0.3) 0%, transparent 50%);
  z-index: 0;
  border-radius: 20px;
}

/* 地图装饰元素 */
.map-decoration {
  position: absolute;
  font-size: 40px;
  opacity: 0.6;
  z-index: 1;
  pointer-events: none;
}

.map-decoration.cloud {
  animation: float 6s ease-in-out infinite;
}

.map-decoration.cloud-1 {
  top: 10%;
  left: 15%;
  animation-delay: 0s;
}

.map-decoration.cloud-2 {
  top: 20%;
  right: 20%;
  animation-delay: 2s;
}

.map-decoration.tree {
  bottom: 15%;
  font-size: 50px;
}

.map-decoration.tree-1 {
  left: 5%;
}

.map-decoration.tree-2 {
  right: 5%;
}

.map-decoration.mountain {
  bottom: 10%;
  left: 50%;
  transform: translateX(-50%);
  font-size: 60px;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.map-scroll-container {
  position: relative;
  width: 100%;
  height: 400px;
  overflow: hidden;
  z-index: 2;
}

.map-path-line {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, 
    rgba(102, 126, 234, 0.6) 0%, 
    rgba(118, 75, 162, 0.6) 50%,
    rgba(102, 126, 234, 0.6) 100%);
  transform: translateY(-50%);
  border-radius: 3px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  z-index: 1;
  pointer-events: none;
  width: calc(100% - 400px);
  margin: 0 200px;
}

.levels-container {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  height: 100%;
  min-width: fit-content;
  padding: 0 200px;
  gap: 200px;
  transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.level-node {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  z-index: 3;
  flex-shrink: 0;
  min-width: 150px;
}

.level-node.completed {
  opacity: 1;
}

.level-node.attempted {
  opacity: 0.8;
}

.level-node.current {
  animation: pulse 2s infinite;
}

.level-node.locked {
  opacity: 0.5;
  cursor: not-allowed;
}

.level-point {
  position: relative;
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
  z-index: 4;
}

.trophy-icon {
  font-size: 60px;
  animation: trophy-bounce 2s ease infinite;
  filter: drop-shadow(0 4px 8px rgba(255, 215, 0, 0.5));
}

.level-icon-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  position: relative;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.level-node.completed .level-icon-circle {
  background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
  box-shadow: 0 8px 20px rgba(255, 215, 0, 0.4);
}

.level-node.attempted .level-icon-circle {
  background: linear-gradient(135deg, #FFA500 0%, #FF8C00 100%);
  box-shadow: 0 6px 15px rgba(255, 140, 0, 0.3);
}

.level-node.current .level-icon-circle {
  transform: scale(1.15);
  box-shadow: 0 12px 30px rgba(102, 126, 234, 0.6);
}

.level-node.locked .level-icon-circle {
  background: #95a5a6;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  cursor: not-allowed;
}

.level-icon-circle.locked {
  background: #95a5a6;
}

.level-info-card {
  text-align: center;
  background: white;
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  min-width: 120px;
  transition: all 0.3s ease;
  position: relative;
  z-index: 3;
}

.level-node:hover .level-info-card {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.level-node.locked:hover .level-info-card {
  transform: none;
}

.level-number {
  font-size: 12px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.level-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.level-stars {
  display: flex;
  justify-content: center;
  gap: 2px;
}

.star {
  font-size: 14px;
}

.star.empty {
  opacity: 0.3;
  filter: grayscale(100%);
}

.pulse-ring {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100px;
  height: 100px;
  border: 3px solid #667eea;
  border-radius: 50%;
  animation: pulse-ring 2s infinite;
  z-index: 1;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

@keyframes pulse-ring {
  0% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}

/* 游戏任务界面 */
.game-task-container {
  max-width: 900px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 20px;
}

.level-info-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin-bottom: 5px;
}

.level-info-header p {
  color: #7f8c8d;
  font-size: 14px;
}

.progress-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.progress-bar {
  width: 200px;
  height: 8px;
  background: #ecf0f1;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.progress-text {
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
}

.task-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.word-display {
  text-align: center;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 15px;
  color: white;
}

.word-text {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 20px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.word-text.letter-display {
  font-size: 120px;
  font-weight: 900;
  letter-spacing: 0;
  line-height: 1;
}

.word-details {
  margin-top: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  animation: fadeIn 0.5s ease;
}

.word-meaning {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 15px;
  opacity: 0.95;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 10px;
}

.meaning-label, .phonetic-label {
  font-size: 18px;
  opacity: 0.8;
  font-weight: 400;
}

.meaning-text {
  font-weight: 600;
}

.word-phonetic {
  font-size: 22px;
  font-weight: 500;
  margin-bottom: 15px;
  opacity: 0.95;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 10px;
  font-family: 'Arial', sans-serif;
}

.phonetic-text {
  font-weight: 600;
  font-style: italic;
  color: #FFD700;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
}

.word-examples {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 2px solid rgba(255, 255, 255, 0.3);
}

.examples-label {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  opacity: 0.9;
}

.example-item {
  margin-bottom: 15px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  border-left: 3px solid rgba(255, 255, 255, 0.5);
}

.example-en {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
  font-style: italic;
}

.example-cn {
  font-size: 16px;
  opacity: 0.9;
  color: #FFE5B4;
}

.play-sound-btn {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 0 auto;
  padding: 12px 24px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 25px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.play-sound-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.sound-icon {
  font-size: 20px;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.option-card {
  position: relative;
  background: white;
  border-radius: 15px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 3px solid transparent;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.option-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.option-card.correct {
  border-color: #27ae60;
  background: #d4edda;
  animation: correct-bounce 0.5s ease;
}

.option-card.wrong {
  border-color: #e74c3c;
  background: #f8d7da;
}

.option-card.highlight-correct {
  border-color: #27ae60;
  background: #d4edda;
  animation: highlight-pulse 0.5s ease;
}

.option-card.shake {
  animation: shake 0.5s ease;
}

.option-image {
  width: 100%;
  height: 150px;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 15px;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.option-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.option-letter {
  width: 100%;
  height: 150px;
  border-radius: 10px;
  margin-bottom: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 80px;
  font-weight: 900;
  color: white;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.emoji-fallback {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 80px;
  background: #f8f9fa;
  border-radius: 10px;
}

.emoji-display {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 100px;
  background: linear-gradient(135deg, #fff9e6 0%, #fff5d6 100%);
  border-radius: 10px;
}

.option-text {
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.correct-mark {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 40px;
  height: 40px;
  background: #27ae60;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

.feedback-message {
  text-align: center;
  padding: 20px;
  border-radius: 12px;
  font-size: 20px;
  font-weight: 600;
  animation: fadeIn 0.3s ease;
}

.feedback-message.correct {
  background: #d4edda;
  color: #155724;
}

.feedback-message.wrong {
  background: #f8d7da;
  color: #721c24;
}

.feedback-icon {
  font-size: 28px;
  margin-right: 10px;
}

.next-btn {
  padding: 15px 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0 auto;
  display: block;
}

.next-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

/* 通关奖励界面 */
.reward-container {
  max-width: 600px;
  margin: 0 auto;
  position: relative;
}

.reward-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  position: relative;
  overflow: hidden;
}

.reward-animation {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.confetti {
  position: absolute;
  width: 10px;
  height: 10px;
  background: #FFD700;
  animation: confetti-fall 3s infinite;
}

.confetti:nth-child(1) { left: 10%; animation-delay: 0s; background: #FF6B6B; }
.confetti:nth-child(2) { left: 30%; animation-delay: 0.5s; background: #4ECDC4; }
.confetti:nth-child(3) { left: 50%; animation-delay: 1s; background: #45B7D1; }
.confetti:nth-child(4) { left: 70%; animation-delay: 1.5s; background: #FFA07A; }
.confetti:nth-child(5) { left: 90%; animation-delay: 2s; background: #98D8C8; }

@keyframes confetti-fall {
  0% {
    transform: translateY(-100px) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: translateY(600px) rotate(720deg);
    opacity: 0;
  }
}

.reward-icon {
  font-size: 80px;
  margin-bottom: 20px;
  animation: bounce 1s ease infinite;
}

.reward-content h2 {
  color: #2c3e50;
  font-size: 32px;
  margin-bottom: 10px;
}

.reward-message {
  color: #7f8c8d;
  font-size: 18px;
  margin-bottom: 30px;
}

.reward-stats {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 40px;
  flex-wrap: wrap;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  border-radius: 15px;
  min-width: 150px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
}

.stat-detail {
  font-size: 14px;
  color: #FFD700;
  margin-top: 5px;
  font-weight: 500;
  opacity: 0.9;
}

.reward-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.action-btn.secondary {
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
}

.action-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

/* 成就墙界面 */
.achievements-container {
  max-width: 1000px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.achievements-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.achievements-header h2 {
  color: #2c3e50;
  font-size: 28px;
}

.close-achievements-btn {
  width: 40px;
  height: 40px;
  border: none;
  background: #ecf0f1;
  border-radius: 50%;
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #7f8c8d;
}

.close-achievements-btn:hover {
  background: #e74c3c;
  color: white;
  transform: rotate(90deg);
}

.achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.achievement-card {
  background: white;
  border-radius: 15px;
  padding: 25px;
  text-align: center;
  border: 3px solid #ecf0f1;
  transition: all 0.3s ease;
  opacity: 0.5;
}

.achievement-card.unlocked {
  border-color: #FFD700;
  background: linear-gradient(135deg, #fff9e6 0%, #fff5d6 100%);
  opacity: 1;
  box-shadow: 0 8px 20px rgba(255, 215, 0, 0.3);
}

.achievement-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.achievement-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 10px;
}

.achievement-desc {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 10px;
}

.achievement-date {
  font-size: 12px;
  color: #95a5a6;
  font-style: italic;
}

/* 动画效果 */
@keyframes correct-bounce {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

@keyframes highlight-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-10px); }
  75% { transform: translateX(10px); }
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-20px); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes trophy-bounce {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  25% { transform: translateY(-10px) rotate(-5deg); }
  75% { transform: translateY(-10px) rotate(5deg); }
}

/* 滑动控制按钮 */
.map-controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 20px;
  z-index: 10;
}

.scroll-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: none;
  background: rgba(102, 126, 234, 0.9);
  color: white;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
}

.scroll-btn:hover:not(:disabled) {
  background: rgba(102, 126, 234, 1);
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.scroll-btn:disabled {
  background: rgba(149, 165, 166, 0.5);
  cursor: not-allowed;
  opacity: 0.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-stats {
    width: 100%;
    justify-content: space-around;
  }

  .levels-container {
    padding: 0 50px;
    gap: 80px;
  }
  
  .map-scroll-container {
    height: 350px;
  }
  
  .difficulty-cards {
    grid-template-columns: 1fr;
  }
  
  .map-controls {
    bottom: 10px;
  }
  
  .scroll-btn {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }

  .options-grid {
    grid-template-columns: 1fr;
  }

  .task-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .progress-info {
    width: 100%;
  }

  .progress-bar {
    flex: 1;
  }

  .reward-stats {
    flex-direction: column;
  }

  .achievements-grid {
    grid-template-columns: 1fr;
  }
}

/* 进度查看界面 */
.progress-view-container {
  max-width: 1200px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.progress-view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.progress-view-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0;
}

.close-progress-btn {
  width: 40px;
  height: 40px;
  border: none;
  background: #ecf0f1;
  border-radius: 50%;
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #7f8c8d;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-progress-btn:hover {
  background: #e74c3c;
  color: white;
  transform: rotate(90deg);
}

.progress-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.summary-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 25px;
  border-radius: 15px;
  text-align: center;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.summary-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 10px;
}

.summary-value {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 5px;
}

.summary-detail {
  font-size: 12px;
  opacity: 0.8;
}

.progress-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  border-bottom: 2px solid #ecf0f1;
}

.tab-btn {
  padding: 12px 24px;
  border: none;
  background: transparent;
  color: #7f8c8d;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  transition: all 0.3s ease;
  margin-bottom: -2px;
}

.tab-btn:hover {
  color: #667eea;
}

.tab-btn.active {
  color: #667eea;
  border-bottom-color: #667eea;
}

.progress-records {
  max-height: 600px;
  overflow-y: auto;
}

.progress-record-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #ecf0f1;
  transition: all 0.3s ease;
}

.progress-record-card.passed {
  border-left-color: #27ae60;
  background: linear-gradient(90deg, #d4edda 0%, #ffffff 10%);
}

.progress-record-card.failed {
  border-left-color: #e74c3c;
  background: linear-gradient(90deg, #f8d7da 0%, #ffffff 10%);
}

.progress-record-card:hover {
  transform: translateX(5px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.record-info {
  flex: 1;
}

.record-difficulty {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 5px;
}

.record-level {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.record-status {
  flex-shrink: 0;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.status-badge.passed {
  background: #27ae60;
  color: white;
}

.status-badge.failed {
  background: #e74c3c;
  color: white;
}

.record-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

.record-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.record-label {
  color: #7f8c8d;
  font-weight: 500;
}

.record-value {
  color: #2c3e50;
  font-weight: 600;
}

.view-wrong-words-btn {
  padding: 6px 12px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.view-wrong-words-btn:hover {
  background: #c0392b;
  transform: scale(1.05);
}

.empty-records {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-text {
  font-size: 18px;
}

/* 错误单词模态框 */
.wrong-words-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.wrong-words-modal {
  background: white;
  border-radius: 20px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 25px;
  border-bottom: 2px solid #ecf0f1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
}

.close-modal-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  color: white;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-modal-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(90deg);
}

.modal-content {
  padding: 25px;
  overflow-y: auto;
  flex: 1;
}

.wrong-words-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #ecf0f1;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  color: #7f8c8d;
  font-size: 14px;
}

.info-value {
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
}

.wrong-words-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.wrong-word-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
  border-left: 4px solid #e74c3c;
  transition: all 0.3s ease;
}

.wrong-word-item:hover {
  background: #e9ecef;
  transform: translateX(5px);
}

.word-display-item {
  flex: 1;
}

.word-en {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
}

.word-cn {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 3px;
}

.word-phonetic {
  font-size: 12px;
  color: #95a5a6;
  font-style: italic;
}

.play-word-btn {
  padding: 8px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.play-word-btn:hover {
  background: #5568d3;
  transform: scale(1.05);
}

/* 排行榜界面 */
.leaderboard-container {
  max-width: 1200px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.leaderboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.leaderboard-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0;
}

.close-leaderboard-btn {
  width: 40px;
  height: 40px;
  border: none;
  background: #ecf0f1;
  border-radius: 50%;
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #7f8c8d;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-leaderboard-btn:hover {
  background: #e74c3c;
  color: white;
  transform: rotate(90deg);
}

.leaderboard-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
  border-bottom: 2px solid #ecf0f1;
}

.leaderboard-tabs .tab-btn {
  padding: 12px 24px;
  border: none;
  background: transparent;
  color: #7f8c8d;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  transition: all 0.3s ease;
  margin-bottom: -2px;
}

.leaderboard-tabs .tab-btn:hover {
  color: #667eea;
}

.leaderboard-tabs .tab-btn.active {
  color: #667eea;
  border-bottom-color: #667eea;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #ecf0f1;
  border-top-color: #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.leaderboard-content {
  min-height: 400px;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border-left: 4px solid #ecf0f1;
}

.ranking-item:hover {
  transform: translateX(5px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.ranking-item.current-student {
  background: linear-gradient(90deg, #e8f5e9 0%, #ffffff 10%);
  border-left-color: #4caf50;
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.2);
}

/* 前三名特殊样式 */
.ranking-item.rank-1 {
  background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
  color: white;
  border-left-color: #FFD700;
  box-shadow: 0 8px 25px rgba(255, 215, 0, 0.4);
  transform: scale(1.05);
  z-index: 3;
}

.ranking-item.rank-1:hover {
  transform: scale(1.08);
}

.ranking-item.rank-2 {
  background: linear-gradient(135deg, #C0C0C0 0%, #A0A0A0 100%);
  color: white;
  border-left-color: #C0C0C0;
  box-shadow: 0 6px 20px rgba(192, 192, 192, 0.3);
  transform: scale(1.03);
  z-index: 2;
}

.ranking-item.rank-2:hover {
  transform: scale(1.05);
}

.ranking-item.rank-3 {
  background: linear-gradient(135deg, #CD7F32 0%, #B87333 100%);
  color: white;
  border-left-color: #CD7F32;
  box-shadow: 0 6px 20px rgba(205, 127, 50, 0.3);
  transform: scale(1.02);
  z-index: 1;
}

.ranking-item.rank-3:hover {
  transform: scale(1.04);
}

.rank-number {
  width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: 700;
  flex-shrink: 0;
}

.rank-number .medal {
  font-size: 36px;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

.rank-number .rank-text {
  color: #7f8c8d;
}

.ranking-item.rank-1 .rank-number .rank-text,
.ranking-item.rank-2 .rank-number .rank-text,
.ranking-item.rank-3 .rank-number .rank-text {
  color: white;
}

.student-info {
  flex: 1;
  margin-left: 20px;
}

.student-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
}

.ranking-item.rank-1 .student-name,
.ranking-item.rank-2 .student-name,
.ranking-item.rank-3 .student-name {
  color: white;
}

.student-class {
  font-size: 14px;
  color: #7f8c8d;
  opacity: 0.8;
}

.ranking-item.rank-1 .student-class,
.ranking-item.rank-2 .student-class,
.ranking-item.rank-3 .student-class {
  color: rgba(255, 255, 255, 0.9);
}

.student-stars {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 700;
  color: #667eea;
}

.ranking-item.rank-1 .student-stars,
.ranking-item.rank-2 .student-stars,
.ranking-item.rank-3 .student-stars {
  color: white;
}

.stars-icon {
  font-size: 24px;
}

.stars-value {
  min-width: 40px;
  text-align: right;
}

.empty-leaderboard {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.empty-leaderboard .empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-leaderboard .empty-text {
  font-size: 18px;
}
</style>
